Java tutorial
//package com.java2s; /* * Copyright (c) 2014 tabletoptool.com team. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * rptools.com team - initial implementation * tabletoptool.com team - further development */ import java.awt.Dimension; public class Main { public static void constrainTo(Dimension dim, int size) { boolean widthBigger = dim.width > dim.height; if (widthBigger) { dim.height = (int) ((dim.height / (double) dim.width) * size); dim.width = size; } else { dim.width = (int) ((dim.width / (double) dim.height) * size); dim.height = size; } } public static void constrainTo(Dimension dim, int width, int height) { boolean widthBigger = dim.width > dim.height; constrainTo(dim, widthBigger ? width : height); if ((widthBigger && dim.height > height) || (!widthBigger && dim.width > width)) { int size = (int) Math.round(widthBigger ? (height / (double) dim.height) * width : (width / (double) dim.width) * dim.height); constrainTo(dim, size); } } }