首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么移动矩形是不一致的?

为什么移动矩形是不一致的?
EN

Stack Overflow用户
提问于 2019-06-21 03:06:54
回答 1查看 116关注 0票数 1

我是C#的新手,我正在尝试编写一个简单的程序,允许使用输入来移动矩形。问题是,当在C#中更新矩形的位置时,矩形有时看起来会消失很短的时间,然后在新位置重新出现,而不是一致地移动。

我已经用p5.js和java (Jswing)做过类似的事情。

代码语言:javascript
复制
 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());
    }
}

我希望矩形能够持续移动,而不会有时消失和重新出现。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-21 03:31:55

在winforms中不要这样做。It对图形加速或优化的支持非常有限。

试试wpfuwp,它有很多开箱即用支持的动画功能。

请参阅Microsoft docs

您也可以选择DirectX解决方案,但这将是一种更大的杀伤力。

请注意,这些框架通常使用MVVM模式,在该模式中,您有一个带有代码的Page,一个用作数据源的ViewModel,以及由XAML组成的View

这比普通的老式WinForms更难处理,但如果你正在学习,并且真的想要构建漂亮的应用程序,那么它绝对是一条可行的道路。

WPF动画附带了许多基类/助手类,可以在here中看到

下面是一个示例,纯XAML

代码语言:javascript
复制
<!-- 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>
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56692419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档