c#如何实现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));
}
}
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));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试为您的
Canvas
指定一个固定尺寸,或者至少不要将其居中。如果不这样做,它将采用它包含的元素的大小,这只是带有边距的矩形。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.