Ozzy..
94
开始了:
Dimension imgSize = new Dimension(500, 100);
Dimension boundary = new Dimension(200, 200);
函数根据边界返回新大小
public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
return new Dimension(new_width, new_height);
}
如果任何人还需要图像大小调整代码,这里是一个不错的解决方案.
如果您对上述解决方案不确定,可以采用不同的方法来实现相同的结果.
@Ozzy的答案是正确的,除非不需要缩放(或者更具体地说,当原始宽度小于边界时).将`new_width`和`new_height`初始化为`original_width`和`original_height`可以解决问题. (2认同)
这个答案结束了三天的苦苦挣扎。谢谢。 (2认同)
如果目标尺寸较大,则此方法无效。因此,对于这种方法,“比例”应更改为“缩小”。 (2认同)