<Question> When programming printing code how to measure string? <Answers> Yang Ning: You cant use GraphicsMeasureString Function and must use typographic StringFormat object Reason is: when printing string size is resolutiondependent And if you using MeasureString function or use defaultgraphic StringFormat object it is resolutionindependent the result will be smaller than the true one Below is sample code: Public Shared Function GetTextSize(ByVal g As Graphics _ ByVal text As String _ ByVal textFont As Font) As SizeF If textLength = Then Return New SizeF( ) Dim s As StringFormat = StringFormatGenericTypographic sFormatFlags = StringFormatFlagsMeasureTrailingSpaces Dim textRect As RectangleF Dim characterRanges As CharacterRange() = {New CharacterRange( textLength)} sSetMeasurableCharacterRanges(characterRanges) textRect = gMeasureCharacterRanges(text textFont New RectangleF( ) s)()GetBounds(g) Return New SizeF(textRectRight textRectBottom) End Function BTW: We found a bug when we use code like above The bug is FlexGrids column caption will display disorder So We use following code instead Public Shared Function GetTextSize(ByVal g As Graphics _ ByVal text As String _ ByVal textFont As Font) As SizeF If textLength = Then Return New SizeF( ) Dim s As StringFormat = StringFormatGenericTypographic Dim oldFlags As StringFormatFlags oldFlags = sFormatFlags sFormatFlags = StringFormatFlagsMeasureTrailingSpaces Try Dim textRect As RectangleF Dim characterRanges As CharacterRange() = {New CharacterRange( textLength)} sSetMeasurableCharacterRanges(characterRanges) textRect = gMeasureCharacterRanges(text textFont New RectangleF( ) s)()GetBounds(g) Return New SizeF(textRectRight textRectBottom) Finally StringFormatGenericTypographicFormatFlags = oldFlags End Try End Function |