如何在c#中刷新图形
本文关键字:刷新 图形 | 更新日期: 2023-09-27 17:53:15
我在面板中有一个计时器,当计时器滴答时,它会改变矩形的坐标。
我尝试了两种方法:1. 在onPaint方法中,2. Timer调用一个函数来创建图形并绘制移动的矩形
第一个不工作,但当我切换窗口时,它移动了一次。
第二个解决问题。它在移动,但保留了前一个位置的颜色,这意味着图形没有刷新。
我只是用g.FillRectangles()
来做。
有人能帮我吗?
注:the panel is using a transparent background.
补充道:这是一个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事件中
private void TimerCallback(object sender, EventArgs e)
{
x+=10;
y+=10;
this.Invalidate();
return;
}
remove drawsomething
function。此处不需要。
完整代码:
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);
}
}
重绘后需要调用控件类的Refresh方法。
强制控件立即使其客户端区域无效重绘自身和任何子控件。
您可以使用Invalidate
方法。此方法使控件的特定区域无效,并导致向该控件发送绘制消息。
详情在这里:http://msdn.microsoft.com/ru-ru/library/system.windows.forms.panel.invalidate%28v=vs.110%29.aspx