none
WPF InkCanvas毛笔效果 RRS feed

答案

  • 我们知道在 Inkcanvas.DefaultDrawingAttributes里面可以直接改颜色和大小,但是不能改变Brush 画刷。所以就很难实现所谓毛笔效果 (边缘和内部有点透明的灰色画刷)

    不过还是按照我以前和HeroHua讨论的方式,自定义笔迹类 Stroke, 然后应用上自己的画刷:http://msdn.microsoft.com/zh-cn/library/ms747347.aspx

    我下面的例子供你参考下,你可以顺着修改:

     

      public partial class MainWindow : Window
      {
        public MainWindow()
        {
          InitializeComponent();
        }
    
        bool IsDrawing = false;
        StylusPointCollection pts;
        private void inkcanvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
          IsDrawing = true;
          pts = new StylusPointCollection();
        }
    
        Stroke st = null;
        private void inkcanvas_MouseMove(object sender, MouseEventArgs e)
        {
          if (IsDrawing)
          {
            Point currentPoint = e.GetPosition((IInputElement)sender);
            pts.Add(new StylusPoint(currentPoint.X, currentPoint.Y));
            if (st != null)
              inkcanvas.Strokes.Remove(st);
            st = new BrushStroke(pts);
            inkcanvas.Strokes.Add(st);
          }
        }
    
        private void inkcanvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
          if (st != null)
          {
            inkcanvas.Strokes.Remove(st);
            inkcanvas.Strokes.Add(st.Clone());
          }
          IsDrawing = false;
        }
      }
    
      public class BrushStroke : Stroke
      {
        public BrushStroke(StylusPointCollection pts)
          : base(pts)
        {
          this.StylusPoints = pts;
        }
    
        protected override void DrawCore(DrawingContext drawingContext, DrawingAttributes drawingAttributes)
        {
          Pen pen = new Pen
          {
            Brush = new RadialGradientBrush(Color.FromArgb(0x66, 0x66, 0x66, 0x66),Color.FromArgb(0x00, 0xff,0xff,0xff)),  // 毛笔笔刷渐变色
            Thickness = 50,        //笔尖宽度
            StartLineCap = PenLineCap.Round,
            EndLineCap=PenLineCap.Round
          };
          for (int i = 1; i < StylusPoints.Count; i++)
          {
            drawingContext.DrawEllipse(null, pen, (Point)StylusPoints[i], 1, 1); 
          }
        }
      }
    

    XAML:

     

     

      <Grid>
        <InkCanvas x:Name="inkcanvas" EditingMode="None" Background="Transparent" PreviewMouseMove="inkcanvas_MouseMove" PreviewMouseUp="inkcanvas_MouseUp" PreviewMouseDown="inkcanvas_MouseDown"/>
      </Grid>
    

    Sincerely,

     

     


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    2011年10月10日 18:41
    版主