您也可以按如下 使用它:
public class ImageLabel extends JLabel{
Image image;
int width, height;
public void paint(Graphics g) {
int x, y;
//this is to center the image
x = (this.getWidth() - width) < 0 ? 0 : (this.getWidth() - width);
y = (this.getHeight() - width) < 0 ? 0 : (this.getHeight() - width);
g.drawImage(image, x, y, width, height, null);
}
public void setDimensions(int width, int height) {
this.height = height;
this.width = width;
image = image.getScaledInstance(width, height, Image.SCALE_FAST);
Container parent = this.getParent();
if (parent != null) {
parent.repaint();
}
this.repaint();
}
}
然後,你可以把它放在你的框架和與同放大倍數,爲此我用百分比值放大的方法。
public void zoomImage(int zoomLevel){
int newWidth, newHeight, oldWidth, oldHeight;
ImagePreview ip = (ImagePreview) jLabel1;
oldWidth = ip.getImage().getWidth(null);
oldHeight = ip.getImage().getHeight(null);
newWidth = oldWidth * zoomLevel/100;
newHeight = oldHeight * zoomLevel/100;
ip.setDimensions(newHeight, newWidth);
}
感謝GETAH,我已經有一個方法可以在我的代碼中執行此操作,它只是沒有點擊它,它也可以用於此目的,但正如我剛剛測試的那樣 - 顯然它可以! – Andy 2012-02-18 15:51:04
等待,這種方法似乎影響圖像的透明度(透明位是黑色的),你有什麼想法和更多的如何解決這個問題? – Andy 2012-02-18 15:55:01
@Andy似乎使用AffineTransform應該保留圖像的透明度...檢查了這一點http://stackoverflow.com/a/2176977/782719 – GETah 2012-02-18 16:11:55