I draw brush in picturebox but the location of the drawing appears away from the place of mouse cursor and it always appear on top of the picture Note This happen when sizemode in picture is set to StretchImage
Sub drawBrush(ByVal e As System.Windows.Forms.MouseEventArgs)
Using g As Graphics = Graphics.FromImage(PictureBox1.Image)
Dim x, y As Integer
x = e.Location.X
y = e.Location.Y
Label1.Text = x.ToString
Label2.Text = y.ToString
Width = 2
If x = 0 Then
x = y
End If
Dim brush As SolidBrush = New SolidBrush(color)
Dim pen1 As Pen = New Pen(color, 4)
g.DrawRectangle(pen1, e.X, e.Y, 10, 10)
g.FillRectangle(brush, e.X, e.Y, 10, 10)
End Using
PictureBox1.Invalidate()
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If draw Then
drawBrush(e)
End If
end Sub
CodePudding user response:
When using PictureBoxSizeMode.StretchImage
, that only affects what you see on the screen. The Image
object doesn't change. Let's say that you have an Image
that is 10x10 and a PictureBox
that is 100x100. If you put the mouse pointer in the centre of the control then the location will be (50, 50). If the Image
is only 10x10, how could (50, 50) possibly be used for a point in the Image
? You would need to do some arithmetic to scale your mouse coordinates based on the scaling of the Image
. If the Image
is stretched by N times in a direction then you have to divide the mouse coordinate by N in that direction to map to the corresponding point on the actual Image
:
finalValue = imageDimension * initialValue / controlDimension
That's going to give you a Double
value, so you need to decide what you want to do with that. You might convert it to a Single
and then use the overloads of DrawRectangle
and FillRectangle
that accept Single
values.
CodePudding user response:
I have to use the stretched image after being stretched using PictureBox1.CreateGraphics.DrawRectangle
Private draw As Boolean = False
Private Sub PictureBox1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
draw = True
End Sub
Sub drawBrush(ByVal e As System.Windows.Forms.MouseEventArgs)
Label1.Text = CStr(e.X)
Label2.Text = CStr(e.Y)
PictureBox1.CreateGraphics.DrawRectangle(Pens.Beige, e.X, e.Y, 10, 10)
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
If draw Then
drawBrush(e)
End If
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
draw = False
End Sub