Q: when programming printing code, how to measure string?
A: You can not use Graphics.MeasureString Function, and must use typographic StringFormat object.Reason is: when printing string size is resolution-dependent.And if you using MeasureString function or use defaultgraphic StringFormat object, it is resolution-independent, the RESULT WILL BE SMALLER THAN THE TRUE ONE.
BELOW is Sample Code:
Public Shared Function GetTextSize (Byval TEXT AS STRING, BYVAL TEXTFONT AS FONT) AS SIZEF
If text.length = 0 Then Return new sizef (0, 0)
DIM S as stringFormat = stringformat.Generictypographic
S.FormatFlags = StringFormatFlags.measureTrailingSpaces
DIM TEXTRECT As Rectanglef
Dim CharacterRanges as CharacterRange () = {New CharacterRange (0, Text.Length)}
S.SetMeasurablecharacterRanges (CharacterRanges)
TextRect = G.MeasureCharacterRanges (Text, TextFont, New Rectanglef (0, 0, 4000, 4000), S) (0) .getBounds (g)
Return New Sizef (TextRect.right, TextRect.Bottom)
END FUNCTION
We found a bug. The bug is flexgrid's column caption will display disorder. So we use following code instrument
Public Shared Function GetTextSize (Byval TEXT AS STRING, BYVAL TEXTFONT AS FONT) AS SIZEF
If text.length = 0 Then Return new sizef (0, 0)
DIM S as stringFormat = stringformat.Generictypographic
DIM oldflags as stringformatflags
Oldflags = S.FormatFlags
S.FormatFlags = StringFormatFlags.measureTrailingSpaces
Try
DIM TEXTRECT As Rectanglef
Dim CharacterRanges as CharacterRange () = {New CharacterRange (0, Text.Length)}
S.SetMeasurablecharacterRanges (CharacterRanges)
TextRect = g.MeasureCharacterRanges (Text, TextFont, New Rectanglef (0, 0, 4000, 4000), S) (0) .getBounds (G) Return New Sizef (TextRect.Right, TextRect.Bottom)
Finally
StringFormat.GenericTyPographic.formatFlags = OldFlags
END TRY
END FUNCTION