Algorithm for estimating text width based on contents

前端 未结 8 2270
傲寒
傲寒 2021-02-08 09:11

This is a long shot, but does anyone know of an algorithm for estimating and categorising text width (for a variable width font) based on its contents?

For example, I\'d

8条回答
  •  萌比男神i
    2021-02-08 09:51

    Most GUI frameworks provide some way to calculate text metrics for fonts on given output devices.

    Using java.awt.FontMetrics, for example, I believe you can do this:

    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics; 
    
    public int measureText(Graphics g, String text) {
       g.setFont(new Font("TimesRoman", Font.PLAIN, 12));
       FontMetrics metrics = g.getFontMetrics();
    
       return metrics.stringWidth(text);
    }
    

    Not tested, but you get the idea.


    Under .Net you can use the Graphics.MeasureString method. In C#:

    private void MeasureStringMin(PaintEventArgs e)
    {
    
        // Set up string.
        string measureString = "Measure String";
        Font stringFont = new Font("Arial", 16);
    
        // Measure string.
        SizeF stringSize = new SizeF();
        stringSize = e.Graphics.MeasureString(measureString, stringFont);
    
        // Draw rectangle representing size of string.
        e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
    
        // Draw string to screen.
        e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
    }
    

提交回复
热议问题