gpt4 book ai didi

java - 如何在java中组合两个图标?

转载 作者:搜寻专家 更新时间:2023-11-01 04:06:10 25 4
gpt4 key购买 nike

我有两个图标,一个是透明的,所以我需要添加一个图标,我必须在其上添加透明图标:

  public static void main(String[] args) {
Icon icon = new ImageIcon("0.png");
Icon icon1 = new ImageIcon("2.png");

JLabel label = new JLabel();
label.setIcon(icon);
//label.setIcon(icon1);
JFrame frame = new JFrame();
frame.add(label, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

最佳答案

  • 为每个图标获取一个 BufferedImage
  • 创建一个相同大小的 BufferedImage(我们称之为 combinedImage)。
  • 调用 combinedImage.createGraphics() 获取 Graphics2D(称之为 g)实例。
  • 将非透明图像绘制到 g
  • 将透明图像绘制到g
  • 处置g
  • 使用 combinedImage 作为图标。

例如

Merged Icons

import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

class MergedIcons {

public static void main(String[] args) throws Exception {
URL urlBG = new URL("http://i.stack.imgur.com/gJmeJ.png");
URL urlFG = new URL("/image/5v2TX.png");
final BufferedImage imgBG = ImageIO.read(urlBG);
final BufferedImage imgFG = ImageIO.read(urlFG);
// For simplicity we will presume the images are of identical size
final BufferedImage combinedImage = new BufferedImage(
imgBG.getWidth(),
imgBG.getHeight(),
BufferedImage.TYPE_INT_ARGB );
Graphics2D g = combinedImage.createGraphics();
g.drawImage(imgBG,0,0,null);
g.drawImage(imgFG,0,0,null);
g.dispose();
Runnable r = () -> {
JPanel gui = new JPanel(new GridLayout(1,0,5,5));

gui.add(new JLabel(new ImageIcon(imgBG)));
gui.add(new JLabel(new ImageIcon(imgFG)));
gui.add(new JLabel(new ImageIcon(combinedImage)));

JOptionPane.showMessageDialog(null, gui);
};
SwingUtilities.invokeLater(r);
}
}

关于java - 如何在java中组合两个图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com