这篇文章主要介绍了WPF 在image控件用鼠标拖拽出矩形的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
正文
WPF 在image控件用鼠标拖拽出矩形的实现方法
这篇文章主要介绍了WPF 在image控件用鼠标拖拽出矩形的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
今天有小伙伴问我一个问题,在image控件用鼠标拖拽出矩形,本文告诉大家如何使用鼠标画出矩形
做出来的效果先请大家看一下

最简单的方法是在 down 的时候记录按下的点,在 移动的时候重新计算所在的宽度

先在界面使用一个图片和一个矩形
|
1
2
3
4
5
|
<grid x:name="grid"> <image source="tim截图20180811150831.png"></image> <textblock horizontalalignment="center" verticalalignment="center">欢迎访问我博客 http://lindexi.oschina.io </textblock> <rectangle x:name="rectangle" strokethickness="2" stroke="black" horizontalalignment="left" verticalalignment="top"></rectangle> </grid> |
需要注意,图片的位置需要修改为自己需要的图片
这里的 rectangle 需要做一些设置,主要 horizontalalignment 和 verticalalignment 必须设置为左上角
现在打开 cs 代码,在按下和移动修改矩形
|
1
2
3
|
mousedown += mainwindow_mousedown; mousemove += mainwindow_mousemove; mouseup += mainwindow_mouseup; |
需要两个字段来记录当前是否按下和第一次按下所在的坐标
刚才给 grid 的命名就是为了拿到相对 grid 的坐标
|
1
2
3
4
5
6
7
8
9
10
|
private void mainwindow_mousedown(object sender, mousebuttoneventargs e) { _started = true; _downpoint = e.getposition(grid); } private bool _started; private point _downpoint; |
在鼠标按下时拿到按下的坐标,通过这个坐标就可以计算出矩形所在的位置
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
private void mainwindow_mouseup(object sender, mousebuttoneventargs e) { _started = false; } private void mainwindow_mousemove(object sender, mouseeventargs e) { if (_started) { var point = e.getposition(grid); var rect = new rect(_downpoint, point); rectangle.margin = new thickness(rect.left, rect.top, 0, 0); rectangle.width = rect.width; rectangle.height = rect.height; } } |
代码就是这么简单,通过修改 margin 的方法修改矩形
如果对于高手,我建议使用 rendertransform 的方式而不是使用 margin 这里使用这个方法只是看起来简单
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持米米素材网。
原文链接:https://lindexi.gitee.io/lindexi/post/WPF-在image控件用鼠标拖拽出矩形.html

发表评论