WinForm 使用 Graphics 在控件上写字,以 Buttton 为例

1、在按钮控件的 Button_Paint 事件上绘画

Button button = new System.Windows.Forms.Button();
button.Paint += Button_Paint;

2、事件内容

private void Button_Paint(object sender, PaintEventArgs e)
{
    //得到控件对象
    System.Windows.Forms.Button button = sender as System.Windows.Forms.Button;

    //得到控件绘画对象
    Graphics g = e.Graphics;

    //开始写字  tag里存放按钮上要展示的字
    g.DrawString(button.Tag.ToString(), button.Font, new SolidBrush(button.ForeColor), 0.0f, 0.0f, new StringFormat());

    //刷新
    g.Flush();
} 

3、Graphics.cs 类库提供的 DrawString 方法 参数含义

//
// 摘要:
//     使用指定 System.Drawing.StringFormat 的格式化特性,用指定的 System.Drawing.Brush 和 System.Drawing.Font
//     对象在指定的位置绘制指定的文本字符串。
//
// 参数:
//   s:
//     要绘制的字符串。
//
//   font:
//     System.Drawing.Font,它定义字符串的文本格式。
//
//   brush:
//     System.Drawing.Brush,它确定所绘制文本的颜色和纹理。
//
//   x:
//     所绘制文本的左上角的 x 坐标。
//
//   y:
//     所绘制文本的左上角的 y 坐标。
//
//   format:
//     System.Drawing.StringFormat,它指定应用于所绘制文本的格式化特性(如行距和对齐方式)。
//
// 异常:
//   T:System.ArgumentNullException:
//     brush 为 null。- 或 -s 为 null。
public void DrawString(string s, Font font, Brush brush, float x, float y, StringFormat format); 

4、其他

//测量按钮文本的矩形区域大小
SizeF textSize = g.MeasureString(button.Text, button.Font);

//清除并重新指定按钮背景色 (按钮所有样式都会被清空)
g.Clear(BackColor);
posted @ 2021-06-02 17:15  Journey&Flower  阅读(969)  评论(0)    收藏  举报