How do I find the 4: 3 aspect ratio that fits a given size?

The problem here is that I have a display window of size x by y and I need to display the image inside the window without scrolling and maintain a 4: 3 aspect ratio. I have the following piece of code:

// Lock the current height, calculate new width of the canvas and scale the viewport.
// get width of the movie canvas
qreal width = canvas_->width();

// Find the height of the video
qreal height = (width/4.0) * 3;

// find original width and height for video to calculate scaling factor
qreal videoWidth = movieData_->GetWidth();
qreal videoHeight = movieData_->GetHeight();

// calculate scaling factor
qreal scaleFactorWidth = width/videoWidth;
qreal scaleFactorHeight = height/videoHeight;

      

Of course, using the height or width as an "anchor" somehow the new image will cause scrolling (if the original image is larger than the window in the first place). How do I find the 4: 3 aspect ratio that fits a given size?

Edit I would need to pass a scale factor for x and y to scale

canvas_->scale(scaleFactorWidth, scaleFactorHeight);

      

+2


source to share


4 answers


    struct dimensions resize_to_fit_in(struct dimensions a, struct dimensions b) {
        double wf, hf, f;
        struct dimensions out;

        wf = (double) b.w / a.w;
        hf = (double) b.h / a.h;

        if (wf > hf)
                f = hf;
        else
                f = wf;

        out.w = a.w * f;
        out.h = a.h * f;

        return out;
}

      



Here is Option C, where the returned dimension will be dimension "a" set to dimension "b" without losing aspect ratio.

+2


source


Just take the minimum of both calculated values:

scale = min(scaleFactorWidth, scaleFactorHeight)

      



or (if you want an external fit)

scale = max(scaleFactorWidth, scaleFactorHeight)

      

+5


source


Find the largest of the two values, width, w

and height h

. Let's say the maximum width of x

height is 100 x

80. Note that 100/80 = 1.25.

Case 1: If w/h > 1.25

, divide w

by 100 to get the ratio of the original size to the new size. Then multiply h

by this ratio.

Case 2: Otherwise, divide h

by 80 to get the ratio of the original size to the new size. Then multiply w

by this ratio.

+1


source


Here's the ActionScript version you're asking for (resizing while maintaining aspect ratio) ... shouldn't be too hard to carry over to all:

    private static function resizeTo(dispObj:DisplayObject, width:Number, height:Number) : void
    {
        var ar:Number = width / height;
        var dispObjAr:Number = dispObj.width/dispObj.height;
        if (ar < dispObjAr)
        {
            dispObj.width = width;
            dispObj.height = width / dispObjAr;
        }
        else
        {
            dispObj.height = height;
            dispObj.width = height * dispObjAr;
        }
        return;
    }

      

EDIT: To keep 4: 3 the original images must be 4: 3

+1


source







All Articles