在winform中,自己写了个继承自label的类,实现了一些简单图形的绘制,省的用这些小图标的时候还要用ps做图片再贴进去。
新建一个winforms程序,添加一个CusLabel.cs类,代码如下:
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace TestCusLabel
{
public class CusLabel : Label
{
private int _type = 0;
public int Type
{
get { return _type; }
set
{
_type = value;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
SolidBrush brush = new SolidBrush(ForeColor);
Pen pen = new Pen(brush,1);
GraphicsPath path = new GraphicsPath();
List <PointF> points = new List<PointF>();
switch(Type)
{
case 0://箭头
{
points.Add(new PointF(0,Height*1.0f/3));
points.Add(new PointF(Width* 1.0f * 2 / 3,Height*1.0f/3));
points.Add(new PointF(Width* 1.0f * 2 / 3,0));
points.Add(new PointF(Width, Height * 1.0f / 2));
points.Add(new PointF(Width * 1.0f * 2 / 3, Height));
points.Add(new PointF(Width * 1.0f * 2 / 3, Height * 1.0f*2 / 3));
points.Add(new PointF(0, Height * 1.0f*2 / 3));
points.Add(new PointF(0, Height * 1.0f / 3));
}
break;
case 1://菱形
{
points.Add(new PointF(0,Height*1.0f/2));
points.Add(new PointF(Width * 1.0f / 2,0));
points.Add(new PointF(Width, Height * 1.0f / 2));
points.Add(new PointF(Width * 1.0f / 2,Height));
points.Add(new PointF(0,Height*1.0f/2));
}
break;
case 2://三角形
{
points.Add(new PointF(Width * 1.0f / 2, 0));
points.Add(new PointF(Width,Height));
points.Add(new PointF(0, Height));
points.Add(new PointF(Width * 1.0f / 2, 0));
}
break;
case 3://圆形
{
g.FillEllipse(brush,new Rectangle(0,0,Width,Height));
}
break;
case 4://矩形
{
g.FillRectangle(brush,new Rectangle(0, 0, Width, Height));
}
break;
default:
break;
}
if(Type==0|| Type==1|| Type==2)
{
if (points.Count > 0)
{
path.AddPolygon(points.ToArray());
g.FillPath(brush, path);
}
}
brush.Dispose();
}
}
}
然后重新生成程序,就能在工具箱栏看到自己重写的类了,直接可以拖动到form窗口使用,如下:
同时,可以再属性栏看到我们在CusLabel类中添加的Type属性