我是C#的新手,我正在尝试编写一个简单的程序,允许使用输入来移动矩形。问题是,当在C#中更新矩形的位置时,矩形有时看起来会消失很短的时间,然后在新位置重新出现,而不是一致地移动。
我已经用p5.js和java (Jswing)做过类似的事情。
public class WinFormsTest : Form
{
System.Windows.Forms.Timer timer;
Graphics graphics;
Brush brush;
Rectangle rect = new Rectangle(0, 0, 80, 80);
public WinFormsTest()
{
Draw();
}
public void Draw()
{
Text = "HelloWold";
Height = 800;
Width = 800;
timer = new System.Windows.Forms.Timer();
timer.Interval = 1;
timer.Tick += new EventHandler(timer_Tick);
Invalidate();
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
graphics = CreateGraphics();
brush = new SolidBrush(Color.Green);
graphics.Clear(Color.White);
Random rnd = new Random();
graphics.FillRectangle(brush, rect);
rect.X++;
rect.Y++;
}
public static void Main(string[] args)
{
Application.Run(new WinFormsTest());
}
}
我希望矩形能够持续移动,而不会有时消失和重新出现。
发布于 2019-06-21 03:31:55
在winforms中不要这样做。It对图形加速或优化的支持非常有限。
试试wpf
或uwp
,它有很多开箱即用支持的动画功能。
您也可以选择DirectX
解决方案,但这将是一种更大的杀伤力。
请注意,这些框架通常使用MVVM
模式,在该模式中,您有一个带有代码的Page
,一个用作数据源的ViewModel
,以及由XAML
组成的View
。
这比普通的老式WinForms
更难处理,但如果你正在学习,并且真的想要构建漂亮的应用程序,那么它绝对是一条可行的道路。
WPF动画附带了许多基类/助手类,可以在here中看到
下面是一个示例,纯XAML
<!-- just a container -->
<Canvas Background="Orange">
<-- a canvas to apply the animation on -->
<Canvas x:Name="target" Background="Green">
<!-- your rectangle -->
<Rectangle Width="200" Height="100" Fill="Blue" Stroke="Black" StrokeThickness="4"/>
<!-- the animation trigger -->
<Canvas.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard>
<Storyboard RepeatBehavior="Forever" AutoReverse="True">
<DoubleAnimation Storyboard.TargetName="target"
Storyboard.TargetProperty="Left"
From="0" To="100"
Duration="0:0:3"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Canvas.Triggers>
</Canvas>
</Canvas>
https://stackoverflow.com/questions/56692419
复制相似问题