【问题标题】:Swing - new ImageIcon from ColorSwing - 来自 Color 的新 ImageIcon
【发布时间】:2018-04-18 15:45:51
【问题描述】:

我需要用简单的颜色(比如说蓝色)以编程方式创建一个ImageIcon

所以我开始这样做了:

ImageIcon imageIcon = new ImageIcon();

现在我正在尝试用蓝色填充我的ImageIcon

【问题讨论】:

标签: java image swing colors icons


【解决方案1】:

这应该可以解决问题

BufferedImage image = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();

graphics.setPaint(new Color(0, 0, 128));
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());

ImageIcon imageIcon = new ImageIcon(image);

【讨论】:

    【解决方案2】:

    这是一个例子

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.WindowConstants;
    
    public class CreateImage {
    
        public static void main(String[] args) {
            JFrame frm = new JFrame("Test");
            frm.add(new JLabel(createImage(Color.BLUE, new Dimension(200, 100))));
            frm.pack();
            frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frm.setLocationRelativeTo(null);
            frm.setVisible(true);
        }
    
        public static Icon createImage(Color c, Dimension size) {
            BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
            Graphics g = img.createGraphics();
            g.setColor(c);
            g.fillRect(0, 0, size.width, size.height);
            return new ImageIcon(img);
        }
    }
    

    【讨论】:

      【解决方案3】:

      基于answer Lonely Neuron,我创建了一个方法来创建一个具有所需大小和Color的新ImageIcon

      public static ImageIcon createImageIcon(Color color, int width, int height) {
          BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
          Graphics2D graphics = image.createGraphics();
          graphics.setPaint(color);
          graphics.fillRect (0, 0, width, height);
          return new ImageIcon(image);
      }
      

      这样称呼它:

      ImageIcon imageIcon = createImageIcon(new Color(0, 0, 128), 60, 60);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-01
        • 2011-01-30
        • 1970-01-01
        • 1970-01-01
        • 2018-11-03
        • 1970-01-01
        • 2012-12-30
        相关资源
        最近更新 更多