我想制作一个用鼠标移动和缩放儿童的观察器。
所以,我创建了类TransformViewer : UserControl
并覆盖了一个事件方法。
但是OnMouseMove有问题。当我翻译RenderTransform时,即使我不移动鼠标,也会连续调用OnMouseMove。并且RenderTransform震动。
protected override void OnMouseMove(MouseEventArgs e) {
Point mouse = e.GetPosition( this );
Vector delta = Point.Subtract( mouse, oldMouse );
oldMouse = mouse;
if(Keyboard.IsKeyDown( Key.LeftShift ) &&
(e.LeftButton == MouseButtonState.Pressed || e.RightButton == MouseButtonState.Pressed)) {
Matrix matrix = transform.Matrix;
matrix.Translate( delta.X, delta.Y );
transform.Matrix = matrix;
e.Handled = true;
RenderTransform = transform;
}
}
为什么会这样?
答案 0 :(得分:0)
最好更改孩子的RenderTransform。
public class TransformViewer : UserControl {
private readonly MatrixTransform transform = new MatrixTransform();
private Point pressedMouse;
protected override void OnMouseDown(MouseButtonEventArgs e) {
pressedMouse = transform.Inverse.Transform( e.GetPosition( this ) );
}
protected override void OnMouseMove(MouseEventArgs e) {
if(e.MiddleButton == MouseButtonState.Pressed) {
Point mouse = transform.Inverse.Transform( e.GetPosition( this ) );
Vector delta = Point.Subtract( mouse, pressedMouse ); // delta from old mouse to current mouse
var translate = new TranslateTransform( delta.X, delta.Y );
transform.Matrix = translate.Value * transform.Matrix;
((UIElement) Content).RenderTransform = transform;
e.Handled = true;
}
}
protected override void OnMouseWheel(MouseWheelEventArgs e) {
float scale = 1.1f;
if(e.Delta < 0) scale = 1f / scale;
Point mouse = e.GetPosition( this );
Matrix matrix = transform.Matrix;
matrix.ScaleAt( scale, scale, mouse.X, mouse.Y );
transform.Matrix = matrix;
((UIElement) Content).RenderTransform = transform;
e.Handled = true;
}
}