gpt4 book ai didi

c# - 简单的 WPF 平移;这段代码很接近但不太正确

转载 作者:行者123 更新时间:2023-11-30 12:12:55 40 4
gpt4 key购买 nike

我正在尝试使用 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>

最佳答案

这应该可以工作(插入 bool 变量 isDragged)并替换

var pos = e.GetPosition(canvas);

var pos = e.GetPosition(this);

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
CaptureMouse();
//_last = e.GetPosition(canvas);
_last = e.GetPosition(this);

isDragged = true;
}

protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
ReleaseMouseCapture();
isDragged = false;
}

还有

protected override void OnMouseMove(MouseEventArgs e)
{
if (isDragged == false)
return;

base.OnMouseMove(e);
if (e.LeftButton == MouseButtonState.Pressed && IsMouseCaptured)
{

var pos = e.GetPosition(this);
var matrix = mt.Matrix; // it's a struct
matrix.Translate(pos.X - _last.X, pos.Y - _last.Y);
mt.Matrix = matrix;
_last = pos;

}

}

关于c# - 简单的 WPF 平移;这段代码很接近但不太正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12594853/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com