刚进新公司做的是流水线的仿真系统,其中涉及到要实现放大和滚动的效果,现在来记录一下:
放大缩小效果:
/// <summary>
/// 放大缩小方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void canvas_MouseWheel(object sender, MouseWheelEventArgs e)
{
double ScaleX = 0;
double ScaleY = 0;
double dbl_ZoomX = ((ScaleTransform)(((TransformGroup)(((UIElement)(this.canvas)).RenderTransform)).Children[0])).ScaleX;
double dbl_ZoomY = ((ScaleTransform)(((TransformGroup)(((UIElement)(this.canvas)).RenderTransform)).Children[0])).ScaleY;
((ScaleTransform)(((TransformGroup)(((UIElement)(this.canvas)).RenderTransform)).Children[0])).CenterX = e.GetPosition(canvas).X;
((ScaleTransform)(((TransformGroup)(((UIElement)(this.canvas)).RenderTransform)).Children[0])).CenterY = e.GetPosition(canvas).Y;
if (e.Delta < 0)
{
ScaleX = dbl_ZoomX - 0.1 < 1 ? 0 : dbl_ZoomX - 0.1;
ScaleY = dbl_ZoomY - 0.1 < 1 ? 0 : dbl_ZoomY - 0.1;
}
else if (e.Delta > 0)
{
ScaleX = dbl_ZoomX + 0.1 > 10.0 ? 10.0 : dbl_ZoomX + 0.1;
ScaleY = dbl_ZoomY + 0.1 > 10.0 ? 10.0 : dbl_ZoomY + 0.1;
}
((ScaleTransform)(((TransformGroup)(((UIElement)(this.canvas)).RenderTransform)).Children[0])).ScaleX = ScaleX;
((ScaleTransform)(((TransformGroup)(((UIElement)(this.canvas)).RenderTransform)).Children[0])).ScaleY = ScaleY;
}
this.canvas 修改成您需要放大的控件。
- 并在this.canvas里面添加滚轮事件MouseWheel="canvas_MouseWheel"
- 在canvas里面添加如下代码:
<Canvas.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="1"/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Canvas.RenderTransform>
控件移动效果
/// <summary>
/// 鼠标移动方法
/// </summary>
Point a;
protected Thickness UCMargin;
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.MouseMove += new MouseEventHandler(Window1_MouseMove);
a = e.GetPosition(this);
if (a.X > 0 && a.Y > 0)
{
UCMargin = canvas.Margin;
}
}
void Window1_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Released)
{
this.Cursor = Cursors.SizeAll;
this.MouseLeftButtonUp += new MouseButtonEventHandler(Window1_MouseLeftButtonUp);
Point PCurrent = e.GetPosition(this);
double x = UCMargin.Left + PCurrent.X - a.X;
double y = UCMargin.Top + PCurrent.Y - a.Y;
canvas.Margin = new Thickness(x, y, 0, 0);
}
else
{
this.MouseMove -= new MouseEventHandler(Window1_MouseMove);
this.Cursor = null;
}
}
void Window1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.Cursor = null;
this.MouseMove -= new MouseEventHandler(Window1_MouseMove);
}
想再做一个旋转的效果,不过还没实现,有经验的欢迎赐教。