实现效果:
实现步骤:
1、首先定义拖拽改变类型枚举:
/// <summary>
/// 拖动改变类型
/// </summary>
public enum ChangeType
{
Move = 0,// 移动
ChangeLeftTop = 1,//左上
ChangeRightTop = 2,//右上
ChangeRightBottom = 3,//右下
ChangeLeftBottom = 4,//左下
Other = 5//其他
}
2、修改MyImage自定义控件
(1)添加全局变量:
public ChangeType changeType;//变换类型
private bool isEnter = false;//是否鼠标进入
private bool isCanDragSize = false;//是否可以改变大小
private Rect LTrect, LBrect, RTrect, RBrect;//左上、左下、右上、右下四个方向的矩形
(2)重绘时在图片四个角绘制四个小矩形表示可拖拽改变大小的四个方向:
/// <summary>
/// 重绘
/// </summary>
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (IsSelect)
{
try
{
//绘制边框
Rect rect = new Rect(0, 0, this.Width, this.Height);
Pen p = new Pen(new SolidColorBrush(Colors.Red), 2);
p.DashStyle = DashStyles.Solid;
p.StartLineCap = PenLineCap.Triangle;
dc.DrawRectangle(Brushes.Transparent, p, rect);
//在4个角画出对应的表示方向的小方块
dc.DrawRectangle(new SolidColorBrush(Colors.Red), p, new Rect(0, 0, 5, 5));
dc.DrawRectangle(new SolidColorBrush(Colors.Red), p, new Rect(this.Width - 5, 0, 5, 5));
dc.DrawRectangle(new SolidColorBrush(Colors.Red), p, new Rect(0, this.Height - 5, 5, 5));
dc.DrawRectangle(new SolidColorBrush(Colors.Red), p, new Rect(this.Width - 5, this.Height - 5, 5, 5));
}
catch { }
}
}
(3)注册相关鼠标事件:
public MyImage()
{
this.Stretch = Stretch.Fill;//需要设置Stretch属性,避免拖拽改变宽高时出现异常
this.MouseLeftButtonDown += MyImage_MouseLeftButtonDown;
this.MouseLeftButtonUp += MyImage_MouseLeftButtonUp;
this.MouseEnter += MyImage_MouseEnter;
this.MouseLeave += MyImage_MouseLeave;
this.MouseMove += MyImage_MouseMove;
}
/// <summary>
/// 鼠标按下
/// </summary>
private void MyImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//获取当前坐标
Point p = e.GetPosition(this);
//获取四个方向的矩形
GetESWNRect();
//获取位置
int x = (int)Canvas.GetLeft(this);
int y = (int)Canvas.GetTop(this);
isCanDragSize = true;
//左上
if (IsInThis(p.X, p.Y, LTrect))
{
this.Cursor = Cursors.SizeNWSE;
changeType = ChangeType.ChangeLeftTop;
}
//右上
else if (IsInThis(p.X, p.Y, RTrect))
{
this.Cursor = Cursors.SizeNESW;
changeType = ChangeType.ChangeRightTop;
}
//左下
else if (IsInThis(p.X, p.Y, LBrect))
{
this.Cursor = Cursors.SizeNESW;
changeType = ChangeType.ChangeLeftBottom;
}
//右下
else if (IsInThis(p.X, p.Y, RBrect))
{
this.Cursor = Cursors.SizeNWSE;
changeType = ChangeType.ChangeRightBottom;
}
//中心
else if (p.X > 5 && p.X < this.Width - 5 && p.Y > 5 && p.Y < this.Height - 5)
{
this.Cursor = Cursors.SizeAll;
changeType = ChangeType.Move;
}