get Scaled Rectangle Dimensions - Java 2D Graphics

Java examples for 2D Graphics:Rectangle

Description

get Scaled Rectangle Dimensions

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int originalWidth = 2;
        int originalHeight = 2;
        int maxWidth = 2;
        int maxHeight = 2;
        System.out.println(java.util.Arrays.toString(getScaledDimensions(
                originalWidth, originalHeight, maxWidth, maxHeight)));
    }/*w  w w  . j a  v  a2s . c  o m*/

    public static int[] getScaledDimensions(int originalWidth,
            int originalHeight, int maxWidth, int maxHeight) {
        int[] values = new int[2];
        if (originalWidth <= maxWidth && originalHeight <= maxHeight) {
            values[0] = originalWidth;
            values[1] = originalHeight;
        } else {
            if (originalHeight >= maxHeight && originalWidth <= maxWidth) {
                int outHeight = maxHeight;
                float ratio = (float) originalWidth / originalHeight;
                int outWidth = (int) (ratio * (float) outHeight);
                values[0] = outWidth;
                values[1] = outHeight;
            } else if (originalWidth >= maxWidth
                    && originalHeight <= maxHeight) {
                int outWidth = maxWidth;
                float ratio = (float) originalWidth / originalHeight;
                int outHeight = (int) ((float) outWidth / ratio);
                values[0] = outWidth;
                values[1] = outHeight;
            } else if (originalWidth >= maxWidth
                    && originalHeight >= maxHeight) {
                if (originalHeight > originalHeight) {
                    int outHeight = maxHeight;
                    float ratio = (float) originalWidth / originalHeight;
                    int outWidth = (int) (ratio * (float) outHeight);
                    values[0] = outWidth;
                    values[1] = outHeight;
                } else {
                    int outWidth = maxWidth;
                    float ratio = (float) originalWidth / originalHeight;
                    int outHeight = (int) ((float) outWidth / ratio);
                    values[0] = outWidth;
                    values[1] = outHeight;
                }
            }
        }
        return values;
    }
}

Related Tutorials