John Doe
10/11/2004 5:20:00 PM
Can someone tell me why the text in the follow code is drawn two different
sizes? I'm trying to create a GraphicsPath with an Ellipse and some text
centered in it. I want the Ellipse (but not the inside of the text) to be
part of the control's region. This works, but the String added to the
GraphicsPath is not the expected size (and thus not centered). I added a
call to Graphics.DrawString(...) to draw the text and it draws the expected
size and properly centered. Why doesn't the text added to the GraphicsPath
draw the correct size, and how can I correct this so the text is the proper
size and centered? I assume it has something to do with the fact the the
String is measured in the context of a Graphics object, but drawn in the
GraphicsPath outside of the context of any Graphics object.
Public Class uctTest
Inherits System.Windows.Forms.Button
Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
Dim ButtonPath As Drawing2D.GraphicsPath
Dim ButtonBrush As Brush
Dim ButtonPen As Pen
ButtonPath = New
Drawing2D.GraphicsPath(Drawing2D.FillMode.Alternate)
ButtonPath.AddEllipse(New Rectangle(New Point(0, 0), Me.Size))
Dim TextSize As SizeF = pe.Graphics.MeasureString(Me.Text, Me.Font)
Dim TextLeft As Single = Me.Width / 2.0! - TextSize.Width / 2.0!
Dim TextTop As Single = Me.Height / 2.0! - TextSize.Height / 2.0!
Dim TextPoint As New Point(TextLeft, TextTop)
ButtonPath.AddString(Me.Text, Me.Font.FontFamily, Me.Font.Style,
Me.Font.Size, TextPoint, StringFormat.GenericDefault)
Dim myRegion As New Region(ButtonPath)
Me.Region = myRegion
ButtonBrush = New SolidBrush(Color.Red)
pe.Graphics.FillPath(ButtonBrush, ButtonPath)
ButtonBrush.Dispose()
' Debug: Draw the Text to see what size it is.
' Debug: This draws the text to correct size and properly centered.
' Debug: The Text in the GraphicsPath does not draw the expected
' Debug: size, and thus not centered.
pe.Graphics.DrawString(Me.Text, Me.Font, Brushes.Blue, TextLeft,
TextTop)
End Sub
End Class
-----
Nobody