优秀的编程知识分享平台

网站首页 > 技术文章 正文

自定义Label的各边线宽度和颜色(设置label高度)

nanyue 2024-08-23 18:28:07 技术文章 6 ℃

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace Test

{

/// <summary>

/// 自定义Label的边线宽度和颜色

/// </summary>

public partial class CustomLabel : Label

{

private int leftWidth = 0;//左边线宽度

private int rightWidth = 0;//右边线宽度

private int topWidth = 0;//上边线宽度

private int bottomWidth = 0;//下边线宽度

private Color borderColor = Color.Black;//边线颜色

public CustomLabel()

{

InitializeComponent();

}

/// <summary>

/// 重写paint方法

/// </summary>

/// <param name="e"></param>

protected override void OnPaint(PaintEventArgs e)

{

ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle,

borderColor, leftWidth, ButtonBorderStyle.Solid,

borderColor, topWidth, ButtonBorderStyle.Solid,

borderColor, rightWidth, ButtonBorderStyle.Solid,

borderColor, bottomWidth, ButtonBorderStyle.Solid);

base.OnPaint(e);

}

[Description("左边线宽度"), Category("自定义属性")]

// 控件的自定义属性值

public int LeftWidth

{

get

{

return leftWidth;

}

set

{

leftWidth = value;

// 此处修改,为自定义属性变动时,执行的操作

// 此处当颜色值属性变动时,使用新的颜色,使自定义控件重绘

this.Invalidate();

}

}

[Description("右边线宽度"), Category("自定义属性")]

// 控件的自定义属性值

public int RightWidth

{

get

{

return rightWidth;

}

set

{

rightWidth = value;

this.Invalidate();

}

}

[Description("上边线宽度"), Category("自定义属性")]

// 控件的自定义属性值

public int TopWidth

{

get

{

return topWidth;

}

set

{

topWidth = value;

this.Invalidate();

}

}

[Description("下边线宽度"), Category("自定义属性")]

// 控件的自定义属性值

public int BottomWidth

{

get

{

return bottomWidth;

}

set

{

bottomWidth = value;

this.Invalidate();

}

}

[Description("边线颜色"), Category("自定义属性")]

// 控件的自定义属性值

public Color BorderColor

{

get

{

return borderColor;

}

set

{

borderColor = value;

this.Invalidate();

}

}

/// <summary>

/// 重绘文字

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void LhParentLabel_Paint(object sender, PaintEventArgs e)

{

if (!this.Enabled)

{

drawLabelText(e, ForeColor);

}

}

/// <summary>

/// 绘制文字

/// </summary>

/// <param name="e"></param>

/// <param name="bgColor"></param>

private void drawLabelText(PaintEventArgs e, Color color)

{

string name = this.Text;

Graphics path = e.Graphics;

//绘制文字

Rectangle rect = new Rectangle(0, 0, this.Width, this.Height + 2);

StringFormat sf = new StringFormat();

sf.Alignment = StringAlignment.Center;

sf.LineAlignment = StringAlignment.Center;

path.DrawString(name, this.Font, new SolidBrush(color), rect, sf);

}

}

}

Tags:

最近发表
标签列表