c#如何实现pan?

时间:2011-10-24 12:37:52

标签: c# wpf-controls margin point pan

按下某个键时我需要平移一些图像,但我的代码不起作用。这是一个示例代码。基本上,我尝试做的是在按下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));
    }
}

1 个答案:

答案 0 :(得分:1)

尝试为Canvas提供固定维度,或者至少不要将其置于中心位置。如果不这样做,则需要它所包含的元素的大小,这只是带有边距的矩形。