画布边界回弹实现
上个博文讲了用 WPF 基于Transform实现画布超出边界触发计算
触发了边界松手之后,实现超出边界的部分复位
1、在MouseMove的时候计算是否超出边界,用double resetX ,double resetY 记录需要复位的偏移量
private void UIElement_OnMouseMove(object sender, MouseEventArgs e) { if(e.LeftButton!= MouseButtonState.Pressed || !isMouseDown) return; Point mousePoint = e.GetPosition(canvasGrid); var targetX = tranX + mousePoint.X - startPoint.X; var targetY = tranY + mousePoint.Y - startPoint.Y; trans.X = targetX; trans.Y = targetY; Console.WriteLine($"{trans.X}==={trans.Y}"); //边界检测 //缩放后的尺寸 var scaleWidth = writeBorad.ActualWidth * scaleSize; var scaleHeight = writeBorad.ActualHeight * scaleSize; var gridWidth = canvasGrid.ActualWidth; var gridHeight = canvasGrid.ActualHeight; //x轴最小x坐标 var minX = -(scaleWidth - gridWidth); //y轴最小坐标 var minY = -(scaleHeight - gridHeight); double resetX = 0; double resetY = 0; //x轴左侧坐标越界,缓存到point点 if (targetX > 0) { ////拖拽前在可拖动区域 //if(trans.X<0) targetX = 0; resetX = targetX; isNeedResetX = true; Console.WriteLine("左侧越界了"); } if (targetX < minX) { targetX = minX; resetX = targetX; isNeedResetX = true; Console.WriteLine("右侧越界了"); } if (targetY > 0) { targetY = 0; resetY = targetY; isNeedResetY = true; Console.WriteLine("上侧越界了"); } if (targetY < minY) { targetY = minY; resetY = targetY; Console.WriteLine("下侧越界了"); isNeedResetY = true; } ResetPoint=new Point(resetX,resetY); }
double resetX = 0;
double resetY = 0;
2、在MouseUp的时候,检测判断是否需要执行复位的操作,重新设置TranslateTransform 的 X和Y的值,达到复位的效果
1 private void WriteBorad_OnMouseUp(object sender, MouseButtonEventArgs e) 2 { 3 4 AddElement(e.GetPosition(writeBorad)); 5 6 isMouseDown = false; 7 writeBorad.ReleaseMouseCapture(); 8 9 if (isNeedResetX) 10 { 11 trans.X = ResetPoint.X; 12 } 13 14 if (isNeedResetY) 15 { 16 trans.Y = ResetPoint.Y; 17 } 18 19 isNeedResetY = isNeedResetX = false; 20 ResetPoint =new Point(); 21 22 if (isNeedResetY || isNeedResetX) 23 { 24 Console.WriteLine($"{trans.X}==={trans.Y}"); 25 } 26 }
想要集体的代码样例,请看:WPF 基于Transform实现画布超出边界触发计算