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);
本文作者:Journey&Flower
本文链接:https://www.cnblogs.com/JourneyOfFlower/p/14842066.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步