正样用C#在Winform做出纵向文字标签
目的
在Winform上面建立一个竖直的(纵向的)TextLabel。
Winform文字标签都是水平方向的,网上资料都是画上去,不管清除。 当你修改显示内容的时候会重叠在一起。 你也不能用上次文字背景色再写一遍清除,由于windows平滑边缘效果,使得边缘影子擦不干净。
方法
- 建立一个类,实例化之后,用 System.Drawing.Graphics的方法在form上面画文本。
- 实例保留Graphics对象,就可以用Clear方法清除写过的文本。
- 流程:
实例化对象 》 写文本 》 擦除文本 》写更新的文本
由于制图对象在实例化中已经创建,方便的流程是在每次写文本之前清除文本
代码
实例化、调用显示
VerticalLabel _myVerticalLabel; //声明对象
//Form 实例化
public MYForm()
{
...
//实例化纵向标签
_myVerticalLabel= new VerticalLabel(this);
...
}
void MyMethod()
{
...
_myVerticalLabel.ClearDrawing();
_myVerticalLabel.DrawVerticalString("My words", PositionX, PositionY, Color.Black);
...
}
对象类定义
- 技巧1,纵向标签对象实例化的时候将Winform对象传给标签对象,不然你画不到form上。
- 技巧2,保留formGraphics,这样才能够清除上次的文本
- 改进, 你也可以吧Clear合并到Draw里面,每次先清除一下
class VerticalLabel
{
System.Drawing.Graphics formGraphics;
public VerticalLabel(Form targetForm)
{
formGraphics = targetForm.CreateGraphics();
}
public void DrawVerticalString(string drawString, float x, float y, Color color, int size = 9, string font = "Tahoma")
{
System.Drawing.Font drawFont = new System.Drawing.Font(font, size);
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(color);
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
drawFormat.FormatFlags = StringFormatFlags.DirectionVertical;
formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
drawFont.Dispose();
drawBrush.Dispose();
}
public void ClearDrawing()
{
formGraphics.Clear(SystemColors.Control);
}
}