首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Graphics.DrawString()的中心文本输出

您好!您提到的 Graphics.DrawString() 是一个 C# 中的方法,用于在 Windows 窗体或图像上绘制文本。要在文本中心对齐,您需要使用 TextRenderer 类。以下是一个示例代码,演示如何在指定的矩形区域中以中心对齐方式绘制文本:

代码语言:csharp
复制
using System.Drawing;
using System.Windows.Forms;

public class CenteredTextForm : Form
{
    public CenteredTextForm()
    {
        this.Size = new Size(300, 200);
        this.Paint += OnPaint;
    }

    private void OnPaint(object sender, PaintEventArgs e)
    {
        string text = "Hello, World!";
        Font font = new Font("Arial", 12);
        Rectangle bounds = this.ClientRectangle;

        // 计算文本的大小
        Size textSize = TextRenderer.MeasureText(text, font);

        // 计算文本的位置,使其居中
        Point textPosition = new Point
        {
            X = bounds.X + (bounds.Width - textSize.Width) / 2,
            Y = bounds.Y + (bounds.Height - textSize.Height) / 2
        };

        // 绘制文本
        TextRenderer.DrawText(e.Graphics, text, font, textPosition, Color.Black);
    }
}

在这个示例中,我们使用了 TextRenderer.MeasureText() 方法来计算文本的大小,然后使用矩形的大小和文本大小来计算文本的位置。最后,我们使用 TextRenderer.DrawText() 方法在指定的位置绘制文本。

请注意,这个示例中的代码仅适用于 Windows 窗体应用程序。如果您正在使用其他类型的应用程序,您可能需要使用不同的技术来绘制和对齐文本。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的问答

领券