如何更改VB.NET表单中单个像素的颜色?
感谢。
答案 0 :(得分:2)
Winforms的一个严格要求是,您应该能够在Windows要求时重绘表单。最小化和恢复窗口时会发生这种情况。或者在旧版本的Windows上移动另一个窗口时。
因此,仅仅在窗口上设置像素是不够的,当窗口重绘时,你将失去它们。而是使用位图。另一个负担是您必须保持响应的用户界面,因此您需要在工作线程上进行计算。 BackgroundWorker可以很方便地做到这一点。
执行此操作的一种方法是使用两个位图,一个填充工作人员,另一个填充您显示的位图。例如,每一行像素都会生成工作位图的副本,并将其传递给ReportProgress()。然后,您的ProgressChanged事件处理旧位图并存储新传递的位图并调用Invalidate以强制重新绘制。
答案 1 :(得分:0)
答案 2 :(得分:0)
这是一些演示代码。由于汉斯提到的原因,重绘速度很慢。加快速度的一种简单方法是仅在延迟后重新计算位图。
Public Class Form1
Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
'create new bitmap
If Me.ClientRectangle.Width <= 0 Then Exit Sub
If Me.ClientRectangle.Height <= 0 Then Exit Sub
Using bmpNew As New Bitmap(Me.ClientRectangle.Width, Me.ClientRectangle.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
'draw some coloured pixels
Using g As Graphics = Graphics.FromImage(bmpNew)
For x As Integer = 0 To bmpNew.Width - 1
For y As Integer = 0 To bmpNew.Height - 1
Dim intR As Integer = CInt(255 * (x / (bmpNew.Width - 1)))
Dim intG As Integer = CInt(255 * (y / (bmpNew.Height - 1)))
Dim intB As Integer = CInt(255 * ((x + y) / (bmpNew.Width + bmpNew.Height - 2)))
Using penNew As New Pen(Color.FromArgb(255, intR, intG, intB))
'NOTE: when the form resizes, only the new section is painted, according to e.ClipRectangle.
g.DrawRectangle(penNew, New Rectangle(New Point(x, y), New Size(1, 1)))
End Using
Next y
Next x
End Using
e.Graphics.DrawImage(bmpNew, New Point(0, 0))
End Using
End Sub
Private Sub Form1_ResizeEnd(sender As Object, e As System.EventArgs) Handles Me.ResizeEnd
Me.Invalidate() 'NOTE: when form resizes, only the new section is painted, according to e.ClipRectangle in Form1_Paint(). We invalidate the whole form here to form an entire form repaint, since we are calculating the colour of the pixel from the size of the form. Try commenting out this line to see the difference.
End Sub
End Class