我想知道在Swing中是否有一种方法可以将ImageIcon转换成灰度图像,就像这样:
component.setIcon(greyed(imageIcon));
我想知道在Swing中是否有一种方法可以将ImageIcon转换成灰度图像,就像这样:
component.setIcon(greyed(imageIcon));
GrayFilter.createDisabledImage()
的一个限制是,它旨在为来自不同外观实现的图标创建禁用外观。使用此示例中的ColorConvertOp
,以下图像对比效果:
GrayFilter.createDisabledImage()
:com.apple.laf.AquaLookAndFeel
ColorConvertOp#filter()
:com.apple.laf.AquaLookAndFeel
GrayFilter.createDisabledImage()
:com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
ColorConvertOp#filter()
:com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
/**
* @see https://dev59.com/yWYq5IYBdhLWcg3wmRoD
* @see https://dev59.com/OmfWa4cB1Zd3GeqPl_OJ#12228640
*/
private Icon getGray(Icon icon) {
final int w = icon.getIconWidth();
final int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g2d = image.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
Image gray = GrayFilter.createDisabledImage(image);
return new ImageIcon(gray);
}
你可以使用以下内容:
ImageIcon icon = new ImageIcon("yourFile.gif");
Image normalImage = icon.getImage();
Image grayImage = GrayFilter.createDisabledImage(normalImage);
gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
而不是gc.createCompatibleImage(w, h);
来保持原始图标的半透明性。 - Huxi