熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

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

2022-06-13   來源: .NET編程 
   <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

From:http://tw.wingwit.com/Article/program/net/201311/13206.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.