257.C# 中使用GDI 绘制线的方法与应用

257.C# 中使用GDI 绘制线的方法与应用

首页休闲益智线条链接更新时间:2024-07-27
摘要

在C#开发中,使用GDI (graphics Device Interface Plus)库可以轻松地实现图形绘制功能,包括绘制线条。本文将介绍GDI 中常用的绘制线的方法与属性,并提供一些实际应用的示例。

正文

GDI 是Windows平台上用于图形绘制的API,它提供了丰富的功能来绘制图像、文本、形状等元素。要使用GDI 进行线条绘制,首先需要引入System.Drawing命名空间。

常用方法与属性Pen类的常用属性Graphics类的常用方法1. 绘制一个简单的直角三角形

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(); } 2. 绘制一个彩虹

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(); } } 3. 用DrawArc绘制一个彩虹

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(); } 4. 绘制一个正玄函数

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(); }

查看全文
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved