我正在加载一个 png 格式的按钮图片。但是格式太大了。如何将其宽度和高度调整到定义的范围,但避免使用图像大小。
前:
public JButton createButton(String name, String toolTip) {
Image a = null;
try {
a = ImageIO.read((InputStream) Test.class.getResourceAsStream("/image/menu/" + name + ".png"));
} catch (IOException ex) {
ex.printStackTrace();
}
ImageIcon iconRollover = new ImageIcon(a);
int w = iconRollover.getIconWidth();
int h = iconRollover.getIconHeight();
// get the cursor for this button
Cursor cursor =
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
// make translucent default image
//Image image = screen.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
Graphics2D g = (Graphics2D) a.getGraphics();
Composite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .5f);
g.setComposite(alpha);
g.drawImage(iconRollover.getImage(), 0, 0, null);
g.dispose();
ImageIcon iconDefault = new ImageIcon(a);
ImageIcon iconPressed = new ImageIcon(a);
// create the button
JButton button = new JButton();
button.setIgnoreRepaint(true);
button.setFocusable(false);
button.setToolTipText(toolTip);
button.setBorder(null);
button.setContentAreaFilled(false);
button.setCursor(cursor);
button.setIcon(iconDefault);
button.setRolloverIcon(iconRollover);
button.setPressedIcon(iconPressed);
return button;
}
后:
跟进:
public JButton createButton(String name, String toolTip) {
// Create image
BufferedImage a = null;
try {
a = ImageIO.read((InputStream) P2P.class.getResourceAsStream("/image/menu/" + name + ".png"));
} catch (IOException ex) {
ex.printStackTrace();
}
BufferedImage bi = new BufferedImage(70, 70, BufferedImage.TRANSLUCENT);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(a, 0, 0, 70, 70, null);
g.dispose();
// get the cursor for this button
Cursor cursor =
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
ImageIcon iconRollover = new ImageIcon(bi);
ImageIcon iconDefault = new ImageIcon(bi);
ImageIcon iconPressed = new ImageIcon(bi);
// create the button
JButton button = new JButton();
//button.addActionListener(this);
button.setIgnoreRepaint(true);
button.setFocusable(false);
button.setToolTipText(toolTip);
button.setBorder(null);
button.setContentAreaFilled(false);
button.setCursor(cursor);
button.setIcon(iconDefault);
button.setRolloverIcon(iconRollover);
button.setPressedIcon(iconPressed);
return button;
}