简体   繁体   English

C#如何实现泛?

[英]c# how to implement pan?

I need to pan some images when a key is pressed, but my code doesn't work. 按下某个键时,我需要平移一些图像,但是我的代码不起作用。 Here's a sample code. 这是示例代码。 Basically, what I try to do is "follow" the rectangle while it moves when A/S/D or W Key are pressed 基本上,我尝试做的是在按下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;

//First, I create the rectangle //首先,我创建矩形

        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));
    }
}

Try giving your Canvas a fixed dimension, or at least do not center it. 尝试给您的Canvas一个固定的尺寸,或者至少不要使其居中。 If you don't, it takes the size of the elements it contains, which is only your rectangle with its margins. 如果不这样做,它将采用它包含的元素的大小,这只是带有边距的矩形。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM