0

这是我的代码

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 开始。如果超出,它会从字面上切断文本。为什么是这样?它不应该适用于整个表格吗?

4

1 回答 1

1

您需要将 CreateGraphics 移动到您的子目录中。来自微软的文档

通过 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
于 2012-10-31T22:59:03.080 回答