【发布时间】:2018-04-13 04:34:34
【问题描述】:
我试图通过计算原始图像的宽度百分比和高度百分比来保持纵横比,然后根据百分比设置新高度和新宽度,但我的代码有问题:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
public class Test extends JFrame {
private JPanel principalPanel;
private BufferedImage image;
public Test() {
setSize(600,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
URL url = new
URL("https://boygeniusreport.files.wordpress.com/2017/04/earth.jpg");
image = ImageIO.read(url);
} catch (Exception e) {
System.out.println("Problem loading image");
e.printStackTrace();
}
principalPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = image.getWidth();
int height = image.getHeight();
int wPercentage = (width*100)/(width+height);
int hPercentage = (height*100)/(width+height);
int w = (width+((getHeight()-height)*wPercentage)/hPercentage);
int h = (height+((getWidth()-width)*hPercentage)/wPercentage);
g.drawImage(image,0,0,w,h,this);
}
};
setContentPane(principalPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Test();
}
});
}
}
【问题讨论】:
-
“但是我的代码有问题”定义“错误”
-
width+height?? -
您需要获取图像高度与宽度的比率,然后保持该比率 - 您没有这样做,因为我没有看到您在上面的代码中计算此比率。
width + height在这些计算中没有位置。 -
一些例子here.