views:

1482

answers:

2

I have a PictureBox (its SizeMode property set to Zoom) containing an image, and both may vary in size.

Since the user has to interact with the image directly, I need to be able to convert the PictureBox click coordinates to image coordinates.

What I have done so far, is compare the aspect ratio of the PictureBox to the aspect ratio of the image. For example, if the PictureBox is "more widescreen" in relation to the image (see screenshot), it means the PictureBox will stretch the image to its own height and center it horizontally, showing its background color (in this case red) to the left and right of the image. Then I assume the image's displayed height is the same as PictureBox.Height, and work from there.

There's a problem, though. As you can see in the screenshot (green annotation mine), the white image being stretched to fit (zoomed) inside the red PictureBox leaves a small margin at the bottom.

Click for full-size.

This doesn't happen for all PictureBox.Size / Image.Size combinations, though. This leads me to believe there must be a better way to do this.

A: 

I don't think that there is a way to get the zoom factor. I'm guessing that there might be an error with your math because of the margin at the bottom (maybe you have a one-off error or something of that nature).

Could you post a complete example showing the calculations you are performing?

casperOne
A: 

Sure, I'll do that. I just have to adapt the code to remove the context dependency.

But the margin at the bottom does not come from my code. It comes from the PictureBox itself. Do me a favor and try the following:

Add a PictureBox (PictureBox1) to a Form, dock it to all four sides of the Form. The code should look as follows:

Public Class Form1

    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown

        PictureBox1.SizeMode = PictureBoxSizeMode.Zoom

        PictureBox1.BackColor = Color.Red
        PictureBox1.Image = New Bitmap(PictureBox1.Width, PictureBox1.Height)
        Dim g As Graphics = Graphics.FromImage(PictureBox1.Image)

        g.FillRectangle(Brushes.White, 0, 0, PictureBox1.Image.Width, PictureBox1.Image.Height)

    End Sub

End Class

Run it and resize the Form so that the image is stretched (zoomed) to fill the height of the PictureBox, leaving red bars to the left and right of the white square. Now resize the Form vertically, as slow as you can. You should see a red margin at the bottom every now and then.

The same thing happens with the width and a horizontal resize, showing a margin to the right.

It's because of this small imperfection that I know the zoom factor cannot be calculated the way I have been doing it; the result would only be an approximate. If after trying this you still think the code is relevant, then I'll gladly post it.

Thank you for taking the time to read and respond.

noroom