这是我的代码
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次。我的问题是它只会在表单的左上角绘制字符串,从0,0开始大约260x260。如果它超越,它实际上会切断文本。为什么是这样?它不应该适用于整个表格吗?
答案 0 :(得分:1)
您需要在子内移动CreateGraphics。来自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