最快最简单的解决方案是使用Image.getScaledInstance
g.drawImage(img.getScaledInstance(newWidth, -1, Image. SCALE_SMOOTH), x, y, this);
如果您对负数感到困惑,Java文档说:
如果宽度或高度为负数,则会替换一个值以保持原始图像尺寸的纵横比。如果宽度和高度都是负数,则使用原始图像尺寸。
更新
只是顺便提一句(我的谷歌出了点问题)。
getScaledInstance既不是最快也不是最高质量的方法,但它是最简单的方法。
阅读
The Perils of Image.getScaledInstance获取更多想法。
更新
将图像缩放以适应区域比简单缩放长宽比稍微复杂些。您必须选择是否要使图像“适合”该区域(可能在其周围留下空白区域)或覆盖该区域(使其最小维度适合该区域的最大维度)。
![Fit](https://istack.dev59.com/PMPbZ.webp)
![Fill](https://istack.dev59.com/3T9Gt.webp)
适应与填充
基本上,我使用比例因子来工作
这将返回特定尺寸的缩放因子。我使用它来决定我想要使用哪个因子,基于我需要的算法
public static double getScaleFactor(int iMasterSize, int iTargetSize) {
double dScale = 1;
if (iMasterSize > iTargetSize) {
dScale = (double) iTargetSize / (double) iMasterSize;
} else {
dScale = (double) iTargetSize / (double) iMasterSize;
}
return dScale;
}
这两个方法使用了它。它们只需要两个Dimension
,原始尺寸和目标尺寸。
public static double getScaleFactorToFit(Dimension original, Dimension toFit) {
double dScale = 1d;
if (original != null && toFit != null) {
double dScaleWidth = getScaleFactor(original.width, toFit.width);
double dScaleHeight = getScaleFactor(original.height, toFit.height);
dScale = Math.min(dScaleHeight, dScaleWidth);
}
return dScale;
}
public static double getScaleFactorToFill(Dimension masterSize, Dimension targetSize) {
double dScaleWidth = getScaleFactor(masterSize.width, targetSize.width);
double dScaleHeight = getScaleFactor(masterSize.height, targetSize.height);
double dScale = Math.max(dScaleHeight, dScaleWidth);
return dScale;
}
将图像传递到程序中相对简单(可以直接传递或通过支持方法传递)。例如,您可以在paint
方法中调用此函数。
double factor getScaledFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getSize());
int scaledWidth = image.getWidth() * scale;
int scaledHeight *= image.getWidth() * scale;
This will automatically take care of the aspect ratio for you ;)
更新并扩展示例
public double getScaleFactor(int iMasterSize, int iTargetSize) {
double dScale = 1;
if (iMasterSize > iTargetSize) {
dScale = (double) iTargetSize / (double) iMasterSize;
} else {
dScale = (double) iTargetSize / (double) iMasterSize;
}
return dScale;
}
public double getScaleFactorToFit(Dimension original, Dimension toFit) {
double dScale = 1d;
if (original != null && toFit != null) {
double dScaleWidth = getScaleFactor(original.width, toFit.width);
double dScaleHeight = getScaleFactor(original.height, toFit.height);
dScale = Math.min(dScaleHeight, dScaleWidth);
}
return dScale;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
double scaleFactor = Math.min(1d, getScaleFactorToFit(new Dimension(image.getWidth(), image.getHeight()), getSize()));
int scaleWidth = (int) Math.round(image.getWidth() * scaleFactor);
int scaleHeight = (int) Math.round(image.getHeight() * scaleFactor);
Image scaled = image.getScaledInstance(scaleWidth, scaleHeight, Image.SCALE_SMOOTH);
int width = getWidth() - 1;
int height = getHeight() - 1;
int x = (width - scaled.getWidth(this)) / 2;
int y = (height - scaled.getHeight(this)) / 2;
g.drawImage(scaled, x, y, this);
}