在计算机编程中,绘图是一项非常重要的任务。而在C#中,使用Graphics类的DrawEllipse方法可以方便地绘制椭圆形。但是,如果想要绘制由边框定义的椭圆,我们需要提供一对坐标、高度和宽度的值来确定椭圆的边界。
DrawEllipse(Pen, Rectangle) | 绘制边界 Rectangle 结构指定的椭圆。 |
DrawEllipse(Pen, RectangleF) | 绘制边界 RectangleF 定义的椭圆。 |
DrawEllipse(Pen, Int32, Int32, Int32, Int32) | 绘制一个由边框定义的椭圆,该边框由矩形的左上角坐标、高度和宽度指定。 |
DrawEllipse(Pen, Single, Single, Single, Single) | 绘制一个由边框(该边框由一对坐标、高度和宽度指定)定义的椭圆。 |
一个例子
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//画笔
Pen pen1 = new Pen(Color.Red, 2);
//用矩形确定椭圆大小
Rectangle rect = new Rectangle((this.Width-200)/2,(this.Height-100)/2 , 200, 100);
e.Graphics.DrawEllipse(pen1, rect);
}
重载位置,大小画一个圆形
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
//画笔
Pen pen1 = new Pen(Color.Red, 2);
//直接用位置,大小创建矩形
e.Graphics.DrawEllipse(pen1, (this.Width - 200) / 2, (this.Height - 100) / 2, 200, 200);
}
选中所有label
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e); // 调用基类的OnPaint方法进行基本的绘制
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // 设置图形的绘制模式为抗锯齿,使绘制的图形边缘更平滑
// 遍历窗体中的所有控件
foreach (var item in this.Controls)
{
// 判断当前控件是否为Label类型
if(item.GetType() == typeof(Label))
{
Label label = (Label)item; // 将找到的控件转换为Label类型
Pen pen1 = new Pen(Color.Red, 2); // 创建一个红色、线宽为2的画笔
// 绘制椭圆,椭圆的位置和大小是基于Label的位置和大小计算得出的
// 椭圆的中心与Label的中心对齐,椭圆的直径是Label宽度或高度的两倍
e.Graphics.DrawEllipse(pen1, label.Location.X - label.Width / 2,
label.Location.Y - label.Height / 2, label.Width * 2, label.Height * 2);
}
}
}
在窗体的OnPaint
事件中遍历窗体上的所有控件,如果找到的控件是Label
类型的,则会使用红色画笔在该Label
周围绘制一个椭圆。椭圆的大小是基于Label
的宽度和高度计算的,使得椭圆的直径是Label
的宽度或高度的两倍,并且椭圆的中心与Label
的中心对齐。通过设置SmoothingMode
为AntiAlias
,绘制的椭圆边缘将更加平滑,提高了绘图质量。
本文作者:rick
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!