如何在C#中刷新图形 [英] How to refresh graphics in C#

查看:321
本文介绍了如何在C#中刷新图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在面板上有一个计时器,当计时器打勾时,它会更改矩形的坐标.

I have a timer in a panel and when the timer ticks, it changes the coordinates of a rectangle.

我尝试了两种方法: 1.在onPaint方法中, 2. Timer调用一个函数来创建图形并绘制移动矩形

I have tried two approaches: 1. Inside onPaint method, 2. Timer calls a function to create graphics and draw the moving rectangle

第一个不起作用,但是当我切换窗户时,它移动了一次.

The first one does not work, but when I switch the windows, it moved once.

第二个有问题.它正在移动,但先前的位置仍充满颜色,这意味着图形不会刷新.

The second one works with problem. It is moving but leaving the previous position filled with color, which means the graphics are not refreshed.

我只是使用g.FillRectangles()来做到这一点.

I simply use g.FillRectangles() to do that.

有人可以帮助我吗?

P.S. the panel is using a transparent background.

已添加: 这是一个System.Windows.Form.Timer

Added: This is a System.Windows.Form.Timer

timer = new Timer();
timer.Enabled = false;
timer.Interval = 100;  /* 100 millisec */
timer.Tick += new EventHandler(TimerCallback);

private void TimerCallback(object sender, EventArgs e)
{
    x+=10;
    y+=10;

    //drawsomething();
    return;
}

1.

protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;
    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
    g.FillRectangle(Brushes.Red, x, y, 100, 100);
    base.OnPaint(e);
}

2.

private void drawsomething()
{
    if (graphics == null)
        graphics = CreateGraphics();

    graphics.FillRectangle(Brushes.Red, x, y, 100, 100);
}

推荐答案

this.Invalidate()放在TimerCallback事件中.

Place this.Invalidate() in the TimerCallback event.

private void TimerCallback(object sender, EventArgs e)
{
    x+=10;
    y+=10;

    this.Invalidate();
    return;
}

删除drawsomething功能.这里不需要.

remove drawsomething function. it is not required here.

完整代码:

public partial class Form1 : Form
{
    Timer timer = new Timer();

    int x;
    int y;
    public Form1()
    {
        InitializeComponent();
        timer.Enabled = true;
        timer.Interval = 100;  /* 100 millisec */
        timer.Tick += new EventHandler(TimerCallback);
    }
    private void TimerCallback(object sender, EventArgs e)
    {
        x += 10;
        y += 10;
        this.Invalidate();
        return;
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
        g.FillRectangle(Brushes.Red, x, y, 100, 100);
        base.OnPaint(e);
    }
}

这篇关于如何在C#中刷新图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆