我正在制作一个具有以下布局(MigLayout
)的Java Swing应用程序:
[icon][icon][icon][....]
where icon = jlabel and the user can add more icons
Run Code Online (Sandbox Code Playgroud)
当用户添加或删除图标时,其他图标应缩小或增长.
我的问题非常简单:我有一个JLabel
包含一个ImageIcon
; 我该如何调整此图标的大小?
tro*_*guy 79
试试这个 :
ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it
Image newimg = image.getScaledInstance(120, 120, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
imageIcon = new ImageIcon(newimg); // transform it back
Run Code Online (Sandbox Code Playgroud)
(在这里找到)
Suk*_*hah 62
调整图标大小并不简单.您需要使用Java的图形2D来缩放图像.第一个参数是一个Image类,您可以从ImageIcon
类中轻松获取.您可以使用ImageIcon
类加载图像文件,然后只需调用getter方法即可获取图像.
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
Run Code Online (Sandbox Code Playgroud)
tir*_*irz 27
怎么样?:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Run Code Online (Sandbox Code Playgroud)
发件人:调整图片大小以适合JLabel
小智 5
这样可以保持正确的宽高比。
public ImageIcon scaleImage(ImageIcon icon, int w, int h)
{
int nw = icon.getIconWidth();
int nh = icon.getIconHeight();
if(icon.getIconWidth() > w)
{
nw = w;
nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
}
if(nh > h)
{
nh = h;
nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
}
return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
}
Run Code Online (Sandbox Code Playgroud)