【问题标题】:Issue Using Graphics DrawString On Resize调整大小时使用图形拉绳的问题
【发布时间】:2016-07-14 17:23:58
【问题描述】:

目标

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


我如何构建它?

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

  1. 标签,带有文字“产品信息”。 Dock=顶部
  2. 用户控件,带有“Product #1”的垂直绘制字符串文本。停靠=左
  3. 表格布局面板,其中包含 X 数量的用户控件。 Dock=填充

这是设计视图:

这是绘制“产品 #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

当前问题

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

我尝试将“双缓冲区”属性设置为 true,但没有结果。有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    您需要为您的控件设置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
    

    【讨论】:

    • 好的,我修改了必要的更改。我将 Me.CreateGraphics() 更改为 e.Graphics 并删除了 dispose 调用。虽然我仍然遇到同样的问题。
    • uProductName 的基类是什么。
    • uProductName 是一个用户控件,其中没有任何内容。我只是用它来绘制字符串,然后将 uProductName 插入到另一个名为 uProductInformation 的用户控件中
    • 基类是ControlUserControl?
    • 构造函数修复做到了!谢谢!
    猜你喜欢
    • 2019-12-08
    • 2014-05-28
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多