C# 控件开发-GDI编程
C# Winform原生控件产值是拿不出手的,工控环境对界面要求不高可以将就,稳定就好。然而更多时候需要美化,这里只研究如何美化。
什么是GDI
控件美化少不了GDI+编程基础,GDI+(Graphics Device Interface)是一种绘图装置接口,可将应用程序和绘图硬件分隔,让我们能够编写与装置无关的应用程序。只需要调用GDI提供的API函数绘制一系列图形。
C#使用System.Drawing命名空间和Graphics绘图类,官方api地址:https://learn.microsoft.com/zh-cn/dotnet/api/system.drawing.graphics?view=netframework-4.8。其中列举了一系列的绘图方法。
绘图坐标系
GDI绘图使用坐标系,原点在控件左上角,向右为x轴正方向,向下为y轴正方向。
绘图事件
.Net 控件Control类提供一个OnPaint事件,用于控件绘图使用。
新建一个窗体项目,在属性窗体中找到paint事件,双击自动生成窗体的paint事件代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 绘图事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Rectangle rect = new Rectangle(500, 100, 200, 50);
Rectangle fillRect = new Rectangle(50, 60, 100, 100);
//使用using自动释放Pen
using (Pen p = new Pen(Color.Red, 3))
{
// 画线
g.DrawLine(p, 0, 0, 300, 100);
// 换一种颜色画个矩形
p.Color = Color.FromArgb(200, 200, 200);
// 坐标点(50,60)处画个100*100矩形
g.DrawRectangle(p, fillRect);
// 画椭圆
p.Color = Color.FromArgb(0, 200, 200);
g.DrawEllipse(p, new Rectangle(50, 200, 100, 100));
// 带文字的框
p.Color = Color.FromArgb(0, 0, 0);
g.DrawRectangle(p, rect);
}
using (SolidBrush sb = new SolidBrush(Color.FromArgb(100, 110, 220)))
{
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString("GDI绘图", this.Font, sb, new PointF(500,300),sf);
g.DrawString("矩形中居中的文字", this.Font, sb, rect, sf);
g.FillRectangle(sb, fillRect);
}
}
}
}
效果如图
这些画图API函数可以基本满足控件绘图需要