在C#中,使用GDI+(Graphics Device Interface)可以繪制自定義控件。以下是一個簡單的示例,演示如何使用C# GDI+繪制一個自定義的矩形控件:
首先,創(chuàng)建一個新的Windows Forms應(yīng)用程序項目。
在Form上繪制自定義矩形控件。為此,請在Form的OnPaint
方法中使用Graphics
對象繪制矩形。以下是一個示例代碼:
using System;
using System.Drawing;
using System.Windows.Forms;
public class CustomRectangle : Control
{
private Color _rectangleColor = Color.Blue;
private int _rectangleWidth = 100;
private int _rectangleHeight = 50;
public CustomRectangle()
{
this.DoubleBuffered = true; // 雙緩沖以防止閃爍
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 設(shè)置畫筆和畫刷
using (Graphics g = e.Graphics)
{
using (Brush brush = new SolidBrush(_rectangleColor))
{
// 繪制矩形
g.FillRectangle(brush, 0, 0, _rectangleWidth, _rectangleHeight);
}
}
}
// 設(shè)置矩形的顏色、寬度和高度
public Color RectangleColor
{
get { return _rectangleColor; }
set { _rectangleColor = value; this.Invalidate(); }
}
public int RectangleWidth
{
get { return _rectangleWidth; }
set { _rectangleWidth = value; this.Invalidate(); }
}
public int RectangleHeight
{
get { return _rectangleHeight; }
set { _rectangleHeight = value; this.Invalidate(); }
}
}
Load
事件處理器中,創(chuàng)建一個CustomRectangle
實例并將其添加到Form上,如下所示:private void Form1_Load(object sender, EventArgs e)
{
CustomRectangle customRectangle = new CustomRectangle();
customRectangle.Location = new Point(50, 50);
customRectangle.Size = new Size(200, 100);
this.Controls.Add(customRectangle);
}
現(xiàn)在,當(dāng)您運行應(yīng)用程序時,將顯示一個自定義的矩形控件。您可以通過更改CustomRectangle
類的屬性來更改矩形的顏色、寬度和高度。