How to measure the pixel width of a digit in a given font / size (C#)

后端 未结 5 1803
闹比i
闹比i 2021-01-04 23:53

I am trying to calculate the pixel width of Excel columns, as described in this post, using the official formula from the OpenXML specification. However, in order to apply t

5条回答
  •  伪装坚强ぢ
    2021-01-05 00:32

    Measuring text widths can be a nighmare.. I dont know why they made it so confusing..

    Heres the most accurate way Ive got to measure the length of text :

        protected int _MeasureDisplayStringWidth ( Graphics graphics, string text, Font font )
        {
            if ( text == "" )
                return 0;
    
            StringFormat format = new StringFormat ( StringFormat.GenericDefault );
            RectangleF rect = new RectangleF ( 0, 0, 1000, 1000 );
            CharacterRange[] ranges = { new CharacterRange ( 0, text.Length ) };
            Region[] regions = new Region[1];
    
            format.SetMeasurableCharacterRanges ( ranges );
            format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
    
            regions = graphics.MeasureCharacterRanges ( text, font, rect, format );
            rect = regions[0].GetBounds ( graphics );
    
            return (int)( rect.Right );
        }
    

提交回复
热议问题