Claudia
Claudia

Reputation: 105

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

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

Upvotes: 0

Views: 504

Answers (1)

Mart
Mart

Reputation: 5788

Try giving your Canvas a fixed dimension, or at least do not center it. If you don't, it takes the size of the elements it contains, which is only your rectangle with its margins.

Upvotes: 1

Related Questions