在C# WinForms应用程序中,绘制字符串是一项常见的任务,无论是为了创建自定义控件、图形用户界面元素还是简单的绘图需求。本文将介绍如何使用C#的WinForms库来绘制字符串,并列举一些常用的属性和方法,以及一些示例来帮助你更好地理解如何操作。
DrawString
方法用于在指定位置绘制字符串,它的一般用法如下:
C#using System.Drawing;
Graphics g = this.CreateGraphics();
Font font = new Font("Arial", 12);
Brush brush = new SolidBrush(Color.Black);
string text = "Hello, WinForms!";
g.DrawString(text, font, brush, new PointF(10, 10));
MeasureString
方法用于测量字符串在指定字体下的宽度和高度:
C#SizeF textSize = g.MeasureString(text, font);
float width = textSize.Width;
float height = textSize.Height;
FontFamily
属性用于获取或设置Font对象的字体系列:
C#FontFamily family = new FontFamily("Arial");
Font font = new Font(family, 12);
Size
属性用于获取Font对象的大小:
C#float fontSize = font.Size;
Color
属性用于获取或设置Brush对象的颜色:
C#Brush brush = new SolidBrush(Color.Red);
Color color = brush.Color;
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
string text = "Hello world";
Font font = new Font("Arial", 16);
Brush brush = new SolidBrush(Color.Black);
SizeF textSize = e.Graphics.MeasureString(text, font);
float x = (this.ClientSize.Width - textSize.Width) / 2;
float y = (this.ClientSize.Height - textSize.Height) / 2;
e.Graphics.DrawString(text, font, brush, new PointF(x, y));
}
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
string text = "Hello World";
Font font = new Font("Arial", 16);
Brush textBrush = new SolidBrush(Color.White);
Brush bgBrush = new SolidBrush(Color.Blue);
e.Graphics.FillRectangle(bgBrush, 10, 10, 200, 50); // 绘制背景
e.Graphics.DrawString(text, font, textBrush, new PointF(10, 10));
}
C#protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
string text = "我是一个环型文字的圈圈";
Font font = new Font("Arial", 12);
Brush brush = new SolidBrush(Color.Black);
PointF center = new PointF(ClientSize.Width / 2, ClientSize.Height / 2);
// 计算文本的总角度
float totalAngle = 360;
// 计算每个字符之间的角度间隔
float charAngle = totalAngle / text.Length;
for (int i = 0; i < text.Length; i++)
{
// 计算当前字符的角度
float angle = i * charAngle;
// 将角度转换为弧度
float radians = (angle - 90) * (float)Math.PI / 180;
// 计算字符的位置
PointF charPosition = new PointF(
center.X + (float)Math.Cos(radians) * 100, // 100是半径
center.Y + (float)Math.Sin(radians) * 100
);
// 绘制字符
e.Graphics.DrawString(text[i].ToString(), font, brush, charPosition);
}
}
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!