Hi
I've drawn a grid on top of an image in a picture box. I'd like to be able to tell which 'square' the mouse cursor is in when it's clicked.
The picture will need to be zoomed in and out, so the code will need to be able to adjust the co-ordinates as required.
I've done some googling and cobbled together some code as below to draw the grid - 'PB_Back' is the Picturebox:
Code:Sub draw_grid() Dim Canvas As Graphics Canvas = Graphics.FromImage(PB_Back.Image) Dim GridCol As Color = Color.Black Dim GridBrush As New SolidBrush(GridCol) Dim GridPen As New Pen(GridCol) Dim imgwidth As Integer = PB_Back.Image.Width Dim imgheight As Integer = PB_Back.Image.Height Dim x As Integer = 0 Dim y As Integer = 0 GridPen.Width = 1 For x = 100 To imgwidth Step 100 Canvas.DrawLine(GridPen, x, 0, x, imgheight) x_boxes += 1 Next For y = 100 To imgheight Step 100 Canvas.DrawLine(GridPen, 0, y, imgwidth, y) y_boxes += 1 Next PB_Back.Invalidate() End Sub
What I need is a conversion between the co-ords of the mouse position when it's clicked over the picture and the units used in the image height/width, which I'm having difficulties understanding. I grab the mouse co-ords with the following:
Where _scale is the current zoom level of the picture (starts at 1, goes up/down in 0.25 steps). Mouse X and Y are adjusted so they start from the end of the picturebox which is inside a panel.Code:Dim p As Point = PointToClient(MousePosition) txt_mousex.Text = (p.X - panel_preview.Left - PB_Back.Left) * _scale txt_mousey.Text = (p.Y - panel_preview.Top - PB_Back.Top) * _scale
At _scale=1 the Picturebox Image width is 5310 wide x 3846 high. The mouse position at the bottom/right edges is (approximately) x=1182, y=836
I want to work out which square a click is made in and then the plan is to position a graphic at this point and snap it to the top/left of the grid box that was clicked in.
How can I translate the mouse co-ords so they use the same scale as the image?
Thanks




Reply With Quote
