c# GDI

C#中怎么使用GDI绘制动态矩形

小亿
102
2023-08-06 01:26:12
栏目: 编程语言

在C#中使用GDI绘制动态矩形,可以使用Graphics类的相关方法来实现。

下面是一个示例代码,演示如何使用GDI绘制动态矩形:

using System;
using System.Drawing;
using System.Windows.Forms;
public class DrawingForm : Form
{
private Timer timer;
private int x, y, width, height;
private bool expanding;
public DrawingForm()
{
this.timer = new Timer();
this.timer.Interval = 50; // 设置定时器的间隔时间为50毫秒
this.timer.Tick += Timer_Tick;
this.x = 100;
this.y = 100;
this.width = 100;
this.height = 100;
this.expanding = true;
this.Paint += DrawingForm_Paint;
this.timer.Start(); // 启动定时器
}
private void Timer_Tick(object sender, EventArgs e)
{
if (this.expanding)
{
if (this.width < 200)
{
this.width += 5;
}
else
{
this.expanding = false;
}
}
else
{
if (this.width > 100)
{
this.width -= 5;
}
else
{
this.expanding = true;
}
}
this.Invalidate(); // 使窗体无效,触发重绘
}
private void DrawingForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Red);
g.DrawRectangle(pen, this.x, this.y, this.width, this.height);
pen.Dispose();
g.Dispose();
}
public static void Main(string[] args)
{
Application.Run(new DrawingForm());
}
}

在这个示例代码中,我们创建了一个继承自Form的DrawingForm类,然后在构造函数中初始化定时器,并设置定时器的Interval属性为50毫秒。然后,我们定义了一些变量来控制矩形的位置和大小,并在Paint事件中使用Graphics对象的DrawRectangle方法来绘制矩形。在定时器的Tick事件中,我们通过改变矩形的大小来实现动态效果,并在每次改变后调用Invalidate方法使窗体无效,从而触发重绘。

最后,在Main方法中,我们使用Application.Run方法来启动应用程序,并创建DrawingForm对象来显示窗体。

0
看了该问题的人还看了