C#中计算字符串文本所占的尺寸 [TextRenderer.MeasureText]

本文介绍了一种在Windows窗体中使用TextRenderer.MeasureText方法精确测量文本尺寸的技术,并通过示例代码展示了如何结合多种字体样式和TextFormatFlags来实现文本的高效绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提供的尺寸,以像素为单位指定的文本时使用指定的字体,使用指定的大小创建初始边框绘制。

命名空间:   System.Windows.Forms
程序集:  System.Windows.Forms(位于 System.Windows.Forms.dll)

 

下面的代码示例演示如何使用其中一个 MeasureText 方法。 若要运行本示例,请将代码粘贴到一个 Windows 窗体并调用

private static void DrawALineOfText(PaintEventArgs e) 
{ 
    // Declare strings to render on the form. 
    string[] stringsToPaint = { "Tail", "Spin", " Toys" }; 
 
    // Declare fonts for rendering the strings. 
    Font[] fonts = { new Font("Arial", 14, FontStyle.Regular),  
        new Font("Arial", 14, FontStyle.Italic),  
        new Font("Arial", 14, FontStyle.Regular) }; 
 
    Point startPoint = new Point(10, 10); 
 
    // Set TextFormatFlags to no padding so strings are drawn together. 
    TextFormatFlags flags = TextFormatFlags.NoPadding; 
 
    // Declare a proposed size with dimensions set to the maximum integer value. 
    Size proposedSize = new Size(int.MaxValue, int.MaxValue); 
 
    // Measure each string with its font and NoPadding value and  
    // draw it to the form. 
    for (int i = 0; i < stringsToPaint.Length; i++) 
    { 
        Size size = TextRenderer.MeasureText(e.Graphics, stringsToPaint[i],  
            fonts[i], proposedSize, flags); 
        Rectangle rect = new Rectangle(startPoint, size); 
        TextRenderer.DrawText(e.Graphics, stringsToPaint[i], fonts[i], 
            startPoint, Color.Black, flags); 
        startPoint.X += size.Width; 
    } 
 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值