【问题标题】:DrawString only works in top-left part of form vb.netDrawString 仅适用于表单 vb.net 的左上部分
【发布时间】:2012-10-31 22:45:22
【问题描述】:

这是我的代码

Public Class Form1

Public MyFormObject As Graphics = Me.CreateGraphics
Public objFont = New System.Drawing.Font("arial", 20)
Public a, b As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Randomize()
    For i = 1 To 10
        a = CInt(Int(Rnd() * Me.Width))
        b = CInt(Int(Rnd() * Me.Height))
        MyFormObject.DrawString("text", objFont, System.Drawing.Brushes.Black, a, b)
    Next
End Sub
End Class

如您所见,我有一个按钮可以在表单中随机绘制字符串“text” 10 次。我的问题是它只会在表单的左上角绘制字符串,大约 260x260 从 0,0 开始。如果超出,它会从字面上切断文本。为什么是这样?它不应该适用于整个表单吗?

【问题讨论】:

    标签: .net vb.net visual-studio-2010 system.drawing drawstring


    【解决方案1】:

    您需要将 CreateGraphics 移动到您的 sub 中。来自Microsoft's documentation

    您通过 CreateGraphics 检索的 Graphics 对象 方法通常不应在当前 Windows 之后保留 消息已被处理,因为使用该对象绘制的任何内容 将在下一条 WM_PAINT 消息中删除。 因此你不能 缓存 Graphics 对象以供重用

    Public Class Form1
    
        Public objFont = New System.Drawing.Font("arial", 20)
        Public a, b As Integer
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            Dim MyFormObject As Graphics = Me.CreateGraphics
    
            Randomize()
            For i = 1 To 10
                a = CInt(Int(Rnd() * Me.Width))
                b = CInt(Int(Rnd() * Me.Height))
                MyFormObject.DrawString("text", objFont, System.Drawing.Brushes.Black, a, b)
            Next
    
            MyFormObject.Dispose
    
        End Sub
    
    End Class
    

    【讨论】:

    • 非常感谢,这一直困扰着我。
    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多