电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

在打印时如何度量字符串?


发布日期:2021/2/23
 
<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

上一篇:使用LINQ来简化编程的7个技巧

下一篇:使用MyGeneration创建模板