温馨提示×

C# Graphics文本绘制怎么实现

小亿
130
2023-10-22 14:23:17
栏目: 编程语言

在C#中绘制文本可以使用System.Drawing命名空间中的Graphics类。下面是一个简单的示例代码,演示如何在窗体上绘制文本:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        // 设置文本的字体和颜色
        Font font = new Font("Arial", 12);
        Brush brush = Brushes.Black;

        // 绘制文本
        string text = "Hello, World!";
        Point position = new Point(50, 50);
        g.DrawString(text, font, brush, position);
    }

    private void InitializeComponent()
    {
        this.SuspendLayout();
        // 
        // Form1
        // 
        this.ClientSize = new System.Drawing.Size(300, 200);
        this.Name = "Form1";
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
        this.ResumeLayout(false);
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new Form1());
    }
}

在上述示例中,我们在窗体的Paint事件中创建一个Graphics对象,并使用DrawString方法绘制文本。可以设置字体、颜色和位置来绘制不同样式的文本。

运行该代码,你将会在窗体上看到绘制的文本。

0