WPF Canvas 画区域
2018-06-23 23:03:43来源:未知 阅读 ()
有时候需要实现类似于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); } }
本来还想做个多边形的例子,水平有限,没达到我想要的效果。研究研究再发。
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- HTML连载87-完善内容区域 2020-05-10
- Vue 结合html2canvas和jsPDF实现html页面转pdf 2020-04-25
- HTML连载82-努比亚界面顶部区域和广告区域 2020-04-12
- 10.布局:两栏和主区域在后的三栏布局,实现侧边栏和主区域伪 2020-04-12
- HTML连载79-背景图片定位区域属性、背景颜色 2020-04-01
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash