visualstudio-理解一个涉及paint()的小c代码片段
本文关键字:片段 paint 的小 代码 一个 visualstudio- | 更新日期: 2023-09-27 17:58:03
我是c#的新手(使用visual c#2010),并且正在制作一个简单的游戏,它将有弹跳球类型的东西,
我用图形填充椭圆来做球,现在我有了这个代码,
protected override void OnPaint( PaintEventArgs e)
{
//System.Drawing.Graphics gobj;
gobj = this.CreateGraphics();
Pen pen = new Pen(System.Drawing.Color.LightSkyBlue, 6);
SolidBrush brush = new SolidBrush(System.Drawing.Color.Magenta);
Rectangle myRectangle = new Rectangle((PointToClient(Cursor.Position).X), PointToClient(Cursor.Position).Y, 250, 200);
gobj.DrawRectangle(pen, myRectangle);
gobj.FillEllipse(brush, myRectangle);
}
当我运行这个代码时,我不断地得到许多圆形和矩形,只出现在屏幕的一部分下面,但它不应该只画一个圆形吗??
请帮我理解这个??
使用DrawRectangle方法绘制矩形,然后使用FillEllipse绘制圆形,只需要使用FillElipse。就像Mikant提到的,你不需要创建图形-使用e.graphics
protected override void OnPaint(PaintEventArgs e)
{
SolidBrush brush = new SolidBrush(System.Drawing.Color.Magenta);
e.Graphics.FillEllipse(brush, (this.Height / 2) - 40, (this.Width / 2) - 40, 80, 80);
}
这在形状中心画一个圆。
祝你在实验和学习中好运!
这真的应该是一个注释,但我还没有足够高的权限!
在处理使用Pen和Font等非托管资源的类型时,我会养成使用using语句的好习惯。它将确保IDisposable对象的正确使用。
记住永远不要使用CreateGraphics
方法(尤其是在OnPaint中)。用e.Graphics
替换所有的gobj
并享受