温馨提示×

c# drawstring如何设置文本位置

c#
小樊
130
2024-11-23 00:51:05
栏目: 编程语言

在C#中,使用Graphics类的DrawString方法可以绘制文本。要设置文本位置,您需要使用FontMetrics类来获取文本的宽度和高度,然后使用Point结构来指定文本在Graphics对象上的位置。

以下是一个示例,展示了如何使用DrawString方法设置文本位置:

using System; using System.Drawing; using System.Windows.Forms; public class CustomForm : Form { private string text = "Hello, World!"; private Font font = new Font("Arial", 14); public CustomForm() { this.ClientSize = new Size(300, 200); this.Text = "DrawString Example"; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // 创建一个Graphics对象 Graphics g = e.Graphics; // 设置文本的字体 g.Font = font; // 获取文本的宽度和高度 FontMetrics fm = g.MeasureString(text, font).Height; // 设置文本位置 Point position = new Point(50, 50); // 绘制文本 g.DrawString(text, font, Brushes.Black, position); } } public class Program { [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new CustomForm()); } } 

在这个示例中,我们创建了一个名为CustomForm的自定义窗体类。在OnPaint方法中,我们使用Graphics对象的DrawString方法绘制文本,并通过Point结构设置文本的位置。在这个例子中,我们将文本位置设置为(50, 50)

0