我正在尝试使用其 RenderTransform 对 WPF Canvas 对象执行一些简单的平移。我希望能够按住鼠标按钮并拖动。使用下面的代码,当你点击的时候会有一个奇怪的跳跃。是什么原因造成的?其次,由于没有更好的术语,拖动被拖动的对象是“摇晃”的。这是为什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestWpfZoom
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private Point _last;
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
CaptureMouse();
_last = e.GetPosition(canvas);
base.OnMouseLeftButtonDown(e);
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
ReleaseMouseCapture();
base.OnMouseLeftButtonUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && IsMouseCaptured)
{
var pos = e.GetPosition(canvas);
var matrix = mt.Matrix; // it's a struct
matrix.Translate(pos.X - _last.X, pos.Y - _last.Y);
mt.Matrix = matrix;
_last = pos;
}
base.OnMouseMove(e);
}
}
}
和 XAML:
<Window x:Class="TestWpfZoom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas Name="canvas">
<Canvas.RenderTransform>
<MatrixTransform x:Name="mt"/>
</Canvas.RenderTransform>
<Ellipse Canvas.Left="100" Canvas.Top="100" Fill="Red" Width="100" Height="100"/>
</Canvas>
</Window>