在C#开发中,使用GDI+(Graphics Device Interface Plus)库可以轻松地实现图形绘制功能,包括绘制线条。本文将介绍GDI+中常用的绘制线的方法与属性,并提供一些实际应用的示例。
GDI+是Windows平台上用于图形绘制的API,它提供了丰富的功能来绘制图像、文本、形状等元素。要使用GDI+进行线条绘制,首先需要引入System.Drawing
命名空间。
Pen
类的常用属性Color
:设置或获取画笔的颜色。Width
:设置或获取画笔的宽度。DashStyle
:设置或获取线条的样式(实线、虚线等)。StartCap
和EndCap
:设置或获取线条的起始和结束端点样式。LineJoin
:设置或获取线条的连接方式。Graphics
类的常用方法DrawLine
:绘制线条。DrawLines
:绘制多条线条。DrawArc
:绘制弧线。C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics graphics = e.Graphics;
Pen pen = new Pen(Color.Blue, 3);
Point point1 = new Point(50, 50);
Point point2 = new Point(50, 150);
Point point3 = new Point(150, 150);
graphics.DrawLine(pen, point1, point2);
graphics.DrawLine(pen, point2, point3);
graphics.DrawLine(pen, point3, point1);
graphics.Dispose();
pen.Dispose();
}
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics graphics = e.Graphics;
string[] colors = { "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red" };
for (int i = 0; i < colors.Length; i++)
{
Color color = Color.FromName(colors[i]);
Pen pen = new Pen(color, 20);
graphics.DrawLine(pen, i * 50 + 20, 100, i * 50 + 70, 100);
pen.Dispose();
}
}
DrawArc
绘制一个彩虹C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics graphics = e.Graphics;
// 启用抗锯齿效果
graphics.SmoothingMode = SmoothingMode.AntiAlias;
int centerX = this.ClientSize.Width / 2;
int centerY = this.ClientSize.Height / 2;
string[] colors = { "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red" };
float startAngle = 180.0f; // 起始角度
float sweepAngle = 180.0f; // 扫描角度
for (int i = 0; i < colors.Length; i++)
{
Color color = Color.FromName(colors[i]);
Pen pen = new Pen(color, 30);
RectangleF arcRect = new RectangleF(centerX - i * 30, centerY - i * 30, (i+1) * 60, (i + 1) * 60);
graphics.DrawArc(pen, arcRect, startAngle, sweepAngle);
pen.Dispose();
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.Refresh();
}
C#public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
this.Paint += new PaintEventHandler(SineWavePlot_Paint);
}
private void SineWavePlot_Paint(object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;
int width = this.ClientSize.Width;
int height = 400;
Pen pen = new Pen(Color.Blue, 2);
graphics.SmoothingMode= SmoothingMode.AntiAlias;
// 绘制坐标轴
graphics.DrawLine(pen, 50, height - 50, width - 50, height - 50); // x轴
graphics.DrawLine(pen, 50, 50, 50, height - 50); // y轴
// 绘制平滑的正弦函数曲线
PointF[] dataPoints = new PointF[10001];
double step = (2 * Math.PI) / 10000; // 步长为2π/10000,表示0到2π之间的弧度范围
for (int i = 0; i <= 10000; i++)
{
double x = i * step;
double y = Math.Sin(x); // 正弦函数
int plotX = (int)(x * 100 + width / 10);
int plotY = (int)(y * 100 + height / 2);
dataPoints[i] = new PointF(plotX, plotY);
}
graphics.DrawLines(pen, dataPoints);
pen.Dispose();
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.Refresh();
}
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!