Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# drawstring

作者:翔龙天下   发布日期:2025-07-12   浏览:51

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

public class DrawStringExample : Form
{
    public DrawStringExample()
    {
        this.Text = "DrawString Example";
        this.Size = new Size(300, 200);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // 创建一个Graphics对象,用于绘制
        Graphics g = e.Graphics;

        // 定义要绘制的字符串
        string text = "Hello, C# Drawing!";

        // 创建字体和画刷
        Font font = new Font("Arial", 16);
        SolidBrush brush = new SolidBrush(Color.Black);

        // 使用DrawString方法绘制字符串
        g.DrawString(text, font, brush, new PointF(50, 50));

        // 释放资源
        brush.Dispose();
        font.Dispose();
    }

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

解释说明:

  1. 创建窗体:继承自 Form 类,并设置窗体标题和大小。
  2. 重写 OnPaint 方法:这是在窗体需要重绘时调用的方法。我们在这里进行绘制操作。
  3. 创建 Graphics 对象:通过 PaintEventArgs 获取 Graphics 对象,用于绘制内容。
  4. 定义字符串、字体和画刷:指定要绘制的文本内容、字体样式和颜色。
  5. 调用 DrawString 方法:使用 Graphics 对象的 DrawString 方法绘制文本到指定位置。
  6. 释放资源:确保释放不再使用的字体和画刷对象,以避免内存泄漏。

希望这段代码能帮助你理解如何在 C# 中使用 DrawString 方法绘制文本。

上一篇:c# using()

下一篇:c#httpclient

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# 取字符串最后一个字符

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站