3

如何更改 VB.NET 表单中单个像素的颜色?

谢谢。

4

3 回答 3

2

Winforms 的一个硬性要求是您应该能够在 Windows 要求时重新绘制表单。当您最小化和恢复窗口时会发生这种情况。或者在旧版本的 Windows 上,当您在您的窗口上移动另一个窗口时。

所以仅仅在窗口上设置像素是不够的,当窗口重绘时你会失去它们。而是使用位图。另一个负担是您必须保持用户界面响应,因此您需要在工作线程上进行计算。BackgroundWorker 可以很方便地做到这一点。

一种方法是使用两个位图,一个用于填充工作器,另一个用于显示。例如,每一行像素都会复制工作中的位图并将其传递给 ReportProgress()。然后,您的 ProgressChanged 事件会处理旧位图并存储新传递的位图并调用 Invalidate 以强制重新绘制。

于 2012-04-29T17:16:44.027 回答
0

您可能会从这些资源中受益:设置表单的背景颜色

DeveloperFusion论坛提取像素颜色

于 2012-04-29T16:50:54.203 回答
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
于 2012-04-30T03:35:50.263 回答