0

按下某个键时我需要平移一些图像,但我的代码不起作用。这是一个示例代码。基本上,我尝试做的是在按下 A/S/D 或 W 键时“跟随”矩形移动

public partial class MainWindow : Window
{
    Point pan = new Point();
    double factorPan = 10;

    public MainWindow()
    {
        InitializeComponent();

        canvas.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
        canvas.VerticalAlignment = System.Windows.VerticalAlignment.Center;

//首先,我创建矩形

        Rectangle rec1 = new Rectangle();

        rec1.Width = 50;
        rec1.Height = 50;
        rec1.Fill = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
        rec1.Visibility = System.Windows.Visibility.Visible;

        canvas.Children.Add(rec1);
        Canvas.SetBottom(rec1, -100);
        Canvas.SetLeft(rec1, -100);
        this.KeyDown += new KeyEventHandler(TeclaApretada);
    }

    void TeclaApretada(object sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.W:
                pan.Y = pan.Y - factorPan;
                break;
            case Key.S:
                pan.Y = pan.Y + factorPan;
                break;
            case Key.A:
                pan.X = pan.X + factorPan;
                break;
            case Key.D:
                pan.X = pan.X - factorPan;
                break;
        }
        actualizarCanvas();
    }

    void actualizarCanvas()
    {
        canvas.Margin = new Thickness((pan.X), 0, 0, (pan.Y));
    }
}
4

1 回答 1

1

尝试给你Canvas一个固定的尺寸,或者至少不要居中。如果你不这样做,它会采用它包含的元素的大小,这只是你的矩形及其边距。

于 2011-10-25T14:20:43.983 回答