vb.netwinformsdrawingpicturebox

Why does my SetPixel function not work in my PictureBox?


I have a problem with SetPixel Function In VB.NET

I am trying to set a color of a specified place in the picturebox.

I want to make the point(X : 45,Y : 55) in the color red.

I searched for a function to do that. And I found SetPixel.

I wrote my code in a button.

This is my code :

Private Sub btn_Set_Click(sender As Object, e As EventArgs) Handles btn_Set.Click
  Dim pic1 As New Bitmap(PictureBox1.Image)
  pic1.SetPixel(45, 55, Color.Red)
End Sub

But it doesn't work. When I click on the button. nothing happens.

Why it doesn't work?

Note: there is no image in the picturebox. I just set a backColor to the picturebox.


Solution

  • You can print pixel with Graphics

    You need to import

    Imports System.Drawing.Graphics
    

    I added the drawline as the pixel is not really visible

    Private Sub btn_Set_Click(sender As Object, e As EventArgs) Handles btn_Set.Click
        Dim pic1 As New Bitmap(200, 100)
    
        Dim gr As Graphics
        gr = Graphics.FromImage(pic1)
        Dim p As Pen = New Pen(Color.Red, 2)
        'printline
        gr.DrawLine(p, 30, 30, 45, 55)
        'Print pixel
        gr.FillRectangle(Brushes.Blue, 55, 55, 1, 1)
        PictureBox1.Image = pic1
        PictureBox1.Update()
        PictureBox1.Refresh()
    End Sub