how to measure width of a string precisely?

后端 未结 4 1310
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 05:56

First of all, question How to measure width of character precisely? which is answered, doesn\'t really help for this case, so this isn\'t a duplicate of that.

4条回答
  •  余生分开走
    2020-12-16 06:30

    You just need to eliminate extra width. You can do this by using string format:

    GdipStringFormatGetGenericTypographic()
    

    You could also use:

    float doubleWidth = g.MeasureString(text+text,...).Width;
    float singleWidth = g.MeasureString(text).Width;
    float textWidth = doubleWidth-singleWidth;
    

    This will allow you to work with other languages such as Japanese.

    On codeproject, Pierre Anaud's solution was to use MeasureCharacterRanges, which returns a region matching exactly the bounding box of the specified string:

    static public int MeasureDisplayStringWidth(Graphics graphics, string text, Font font)
    {
        System.Drawing.StringFormat format  = new System.Drawing.StringFormat ();
        System.Drawing.RectangleF   rect    = new System.Drawing.RectangleF(0, 0, 1000, 1000);
        var ranges  = new System.Drawing.CharacterRange(0, text.Length);
        System.Drawing.Region[] regions = new System.Drawing.Region[1];
    
        format.SetMeasurableCharacterRanges (ranges);
    
        regions = graphics.MeasureCharacterRanges (text, font, rect, format);
        rect    = regions[0].GetBounds (graphics);
    
        return (int)(rect.Right + 1.0f);
    }
    

提交回复
热议问题