有时候需要实现类似于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"/>
然后实现他的事件,在之前我们先决定一下到底是什么形状的区域。
1publicstaticShape CreateShape()2{3//矩形区域4returnnewSystem.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 };78}
然后实现三个事件
booldrawFlag =false;
Shape insertShape;
System.Windows.Point startPosition;PRivatevoidMask_MouseLeftButtonDown(objectsender, MouseButtonEventArgs e)
{
insertShape=CreateShape();if(insertShape !=null)
{
drawFlag=true;
Canvas board= senderasCanvas;
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);
}
}privatevoidimage_MouseMove(objectsender, MouseEventArgs e)
{
Canvas board= senderasCanvas;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);
}
}
}privatevoidMask_MouseLeftButtonUp(objectsender, MouseButtonEventArgs e)
{
drawFlag=false;if(insertShape !=null)
{
insertShape.Opacity=1;
System.Windows.Point p= e.GetPosition(senderasCanvas);
Canvas.SetLeft(insertShape, e.GetPosition(board).X);
Canvas.SetTop(insertShape, e.GetPosition(board).Y);
}
}
本来还想做个多边形的例子,水平有限,没达到我想要的效果。研究研究再发。