有时候需要实现类似于QQ截图那样的选择区域功能,这里的区域可以是一条线,圆,矩形等等
实现原理就是一个Canvas做蒙板,然后canvas的三个事件,MouseLeftButtonDown,MouseMove,MouseLeftButtonUp。非常easy!
首先,你要有个canvas
<Canvas Name="videocanvas" Height="288" Width="352" Background="Transparent" MouseMove="image_MouseMove" MouseLeftButtonDown="Mask_MouseLeftButtonDown" MouseLeftButtonUp="Mask_MouseLeftButtonUp"/>
然后实现他的事件,在之前我们先决定一下到底是什么形状的区域。
1 public static Shape CreateShape()2 {3 //矩形区域4 return new System.Windows.Shapes.Rectangle() { Fill = null, Stroke = System.Windows.Media.Brushes.Red, StrokeThickness = 1 };5 //圆形区域6 //return new System.Windows.Shapes.Ellipse() { Fill = null, Stroke = System.Windows.Media.Brushes.Red, StrokeThickness = 1 };7 8 }
然后实现三个事件
bool drawFlag = false;Shape insertShape;System.Windows.Point startPosition;PRivate void Mask_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){ insertShape = CreateShape(); if (insertShape != null) { drawFlag = true; Canvas board = sender as Canvas; board.Children.Clear(); startPosition = e.GetPosition(board); insertShape.Opacity = 1; Canvas.SetLeft(insertShape, e.GetPosition(board).X); Canvas.SetTop(insertShape, e.GetPosition(board).Y); board.Children.Add(insertShape); }}private void image_MouseMove(object sender, MouseEventArgs e){ Canvas board = sender as Canvas; if (drawFlag && insertShape != null) { if (e.GetPosition(board).X > startPosition.X) { insertShape.Width = e.GetPosition(board).X - startPosition.X; } else { insertShape.Width = startPosition.X - e.GetPosition(board).X; Canvas.SetLeft(insertShape, e.GetPosition(board).X); } if (e.GetPosition(board).Y > startPosition.Y) { insertShape.Height = e.GetPosition(board).Y - startPosition.Y; } else { insertShape.Height = startPosition.Y - e.GetPosition(board).Y; Canvas.SetTop(insertShape, e.GetPosition(board).Y); } }}private void Mask_MouseLeftButtonUp(object sender, MouseButtonEventArgs e){ drawFlag = false; if (insertShape != null) { insertShape.Opacity = 1; System.Windows.Point p = e.GetPosition(sender as Canvas); Canvas.SetLeft(insertShape, e.GetPosition(board).X); Canvas.SetTop(insertShape, e.GetPosition(board).Y); }}
本来还想做个多边形的例子,水平有限,没达到我想要的效果。研究研究再发。
新闻热点
疑难解答