如何在Swing上将ImageIcon变为灰色 [英] How to turn ImageIcon to gray on Swing

查看:139
本文介绍了如何在Swing上将ImageIcon变为灰色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Swing是否有某种方法可以将ImageIcon转换为灰度等级:

I would like to know if there is some way in Swing to turn an ImageIcon to gray scale in a way like:

component.setIcon(greyed(imageIcon));


推荐答案

GrayFilter的一个限制。 createDisabledImage()是它旨在为不同的Look& amp;中的图标创建禁用的外观。感觉实现。使用此 ColorConvertOp 示例,以下图像对比了效果:

One limitation of GrayFilter.createDisabledImage() is that it is designed to create a disabled appearance for icons across diverse Look & Feel implementations. Using this ColorConvertOp example, the following images contrast the effect:

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);
}

这篇关于如何在Swing上将ImageIcon变为灰色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆