在调整大小时使用图形DrawString的问题

时间:2016-07-14 17:23:58

标签: vb.net winforms user-controls gdi+ drawstring

目标

我想在用户控件的左侧显示一个垂直文本,让用户知道他们正在创建/编辑哪个产品。像这样:

enter image description here

我是如何构建它的?

此用户控件由三个控件组成。

  1. 标签,带有文字“产品信息”。坞=顶部
  2. 用户控制,其垂直绘制字符串文本为“Product#1”。坞=左
  3. 表格布局面板,其中包含X个用户控件。坞=填充
  4. 这是设计视图:

    enter image description here

    以下是我的产品名称用户控件的代码,用于绘制“Product#1”

    Public Class uProductName
        Public drawString As String = "Product #1"
    
        Protected Overrides Sub OnPaint(e As PaintEventArgs)
            ' Call the OnPaint method of the base class.
            MyBase.OnPaint(e)
            ' Call methods of the System.Drawing.Graphics object.
            DrawVerticalString(e)
        End Sub
    
        Public Sub DrawVerticalString(ByVal e As PaintEventArgs)
            Dim formGraphics As System.Drawing.Graphics = Me.CreateGraphics()
            Dim drawFont As New System.Drawing.Font("Arial", 20)
            Dim drawBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Black)
            Dim stringSize As New SizeF
            stringSize = e.Graphics.MeasureString(drawString, drawFont)
            Dim x As Single = (Me.Width / 2) - (stringSize.Height / 2)
            Dim y As Single = (Me.Height / 2) - (stringSize.Width / 2)
            Dim drawFormat As New System.Drawing.StringFormat
            drawFormat.FormatFlags = StringFormatFlags.DirectionVertical
            formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat)
    
            drawFormat.Dispose()
            drawFont.Dispose()
            drawBrush.Dispose()
            formGraphics.Dispose()
        End Sub
    End Class
    

    当前问题

    当我开始选择按钮时,表格布局面板会展开以显示更多选项,“Product#1”文本开始出现故障。见下文:

    enter image description here

    我尝试将“Double Buffer”属性设置为true,但结果不是。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您需要为控件设置ControlStyles.ResizeRedraw样式,以指示控件在调整大小时是否重绘。

此外,不使用CreateGraphics(),而是使用OnPaint方法的图形对象,永远不会将其丢弃,因为它不属于您。

Public Sub New()
    ' If the base class is Control, comment the next line
    InitializeComponent()

    Me.SetStyle(ControlStyles.ResizeRedraw, True)
End Sub

Public Sub DrawVerticalString(ByVal e As PaintEventArgs)
    Dim formGraphics As System.Drawing.Graphics = e.Graphics
    '...
End Sub