C#グラフィックスでテキストを描画するにはどうすればよいか

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メソッドを使って文字を描画しました。フォントや色、位置を設定することで、さまざまなスタイルの文字が描画できます。

コードを実行すると、フォームに描画されたテキストが表示されます。

bannerAds