You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中PictureBox的SetPixel函数无效问题咨询

问题原因及解决办法

核心问题有两个:

  • 你仅给PictureBox设置了背景色,未加载图片,此时PictureBox1.Image为null,用它创建的Bitmap对象无效,无法执行SetPixel操作。
  • 即便有有效的Bitmap,你修改后未将其重新赋值给PictureBox1.Image,界面不会自动刷新显示修改内容。

修复后的代码示例:

Private Sub btn_Set_Click(sender As Object, e As EventArgs) Handles btn_Set.Click
    ' 判断PictureBox是否有Image,无则创建与PictureBox尺寸一致的Bitmap
    Dim pic1 As Bitmap
    If PictureBox1.Image Is Nothing Then
        ' 创建匹配PictureBox客户端区域大小的Bitmap
        pic1 = New Bitmap(PictureBox1.ClientSize.Width, PictureBox1.ClientSize.Height)
        ' 填充PictureBox的背景色到Bitmap,保持视觉一致
        Using g As Graphics = Graphics.FromImage(pic1)
            g.Clear(PictureBox1.BackColor)
        End Using
    Else
        pic1 = New Bitmap(PictureBox1.Image)
    End If

    ' 设置指定坐标像素为红色
    pic1.SetPixel(45, 55, Color.Red)
    ' 将修改后的Bitmap赋值回PictureBox,刷新界面
    PictureBox1.Image = pic1
End Sub

补充说明:

  • 当PictureBox无Image时,创建与其客户端尺寸匹配的Bitmap并填充背景色,可保证修改后的效果与原背景衔接自然。
  • 修改Bitmap后必须将其赋值给PictureBox1.Image,才能让界面显示修改后的像素。

内容的提问来源于stack exchange,提问作者user22672706

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:32:10