Christian Cascone
Christian Cascone

Reputation: 483

Issue with calculating the visible area of a zoomed image in a PictureBox in C#

I'm having trouble calculating the visible area of a zoomed image in a PictureBox control in C#. Specifically, I'm trying to calculate a RectangleF that identifies the visible portion of the image within the PictureBox, based on the scaledRect (which specifies the position and size of the zoomed image within the PictureBox), the zoomFactor (which represents the zoom level applied), the size of the PictureBox and the size of the original Image.

I need after to map this RectangleF to the size of the original image.

I've tried a few different approaches, but I haven't been able to get it to work correctly. I've tried this code:

//Calculates the position of the upper left corner of the visible area
    PointF zoomedTopLeft = new PointF(
        (_pictureBox.Width - scaledRect.Width) / 2f - scaledRect.X,
        (_pictureBox.Height - scaledRect.Height) / 2f - scaledRect.Y
    );
    
    // Calculates the size of the visible area of the zoomed image
    float zoomedWidth = _pictureBox.Width / zoomFactor;
    float zoomedHeight = _pictureBox.Height / zoomFactor;
    
    // Convert the coordinates of the upper left corner and the size of the visible area from the zoomed image to the original image
    float visibleLeft = zoomedTopLeft.X / zoomFactor;
    float visibleTop = zoomedTopLeft.Y / zoomFactor;
    float visibleWidth = zoomedWidth / zoomFactor;
    float visibleHeight = zoomedHeight / zoomFactor;
    
    RectangleF visibleRect = new RectangleF(
        visibleLeft, visibleTop, visibleWidth, visibleHeight
    );

Someone knows how to do?

Thanks.

Upvotes: 1

Views: 66

Answers (1)

Christian Cascone
Christian Cascone

Reputation: 483

I found this solution that it's working for me.

private RectangleF GetVisibleRectangle(RectangleF scaledRect) {


            RectangleF imageRect = scaledRect;
            imageRect.Intersect(_containerClientSize);

            float offsetX = 0;
            float offsetY = 0; 

            return new RectangleF(
                (imageRect.X - scaledRect.X + offsetX) / _zoomFactor,
                (imageRect.Y - scaledRect.Y + offsetY) / _zoomFactor,
                imageRect.Width / _zoomFactor,
                imageRect.Height / _zoomFactor
            );


        }

Upvotes: 0

Related Questions