WPF Canvas 画区域

2018-06-18 02:35:16来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

有时候需要实现类似于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
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:菜鸟学习Ado.net笔记一:Ado.net学习之SqlHelper类

下一篇:搭建一套自己实用的.net架构(4)【CodeBuilder-RazorEngine】