10

我想知道 Swing 中是否有某种方法可以将 ImageIcon 转换为灰度,例如:

component.setIcon(greyed(imageIcon));
4

2 回答 2

14

一个限制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://stackoverflow.com/q/14358499/230513
 * @see https://stackoverflow.com/a/12228640/230513
 */
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);
}
于 2013-01-16T13:59:20.797 回答
10

您可以使用以下内容:

ImageIcon icon = new ImageIcon("yourFile.gif");
Image normalImage = icon.getImage();
Image grayImage = GrayFilter.createDisabledImage(normalImage);
于 2013-01-16T12:28:06.743 回答