在打印时如何度量字符串?
点击次数:17 次 发布日期:2008-11-27 00:16:49 作者:源代码网
|
源代码网推荐 When programming printing code, how to measure string? 源代码网推荐 <Answers> 源代码网推荐 Yang Ning: 源代码网推荐 You can"t 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 g As Graphics, _ 源代码网推荐 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 源代码网推荐 源代码网推荐 BTW: 源代码网推荐 We found a bug when we use code like above. The bug is FlexGrid"s 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 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 源代码网推荐 源代码网供稿. |
