java绘制半透明图片_如何使绘制的图像在Java中透明
正如另一個提到的答案,最簡單的方法可能是簡單地使用具有透明背景的PNG圖像(您可以使用像GIMP這樣的圖像編輯器創(chuàng)建這些圖像).或者,如果您僅限于具有純色背景的PNG圖像,以下是如何將PNG中的給定顏色(例如白色)更改為透明的示例:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class SimpleFrame extends JFrame {
JPanel mainPanel = new JPanel() {
ImageIcon originalIcon = new ImageIcon("~/Pictures/apple.png");
ImageFilter filter = new RGBImageFilter() {
int transparentColor = Color.white.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == transparentColor) {
return 0x00FFFFFF & rgb;
} else {
return rgb;
}
}
};
ImageProducer filteredImgProd = new FilteredImageSource(originalIcon.getImage().getSource(), filter);
Image transparentImg = Toolkit.getDefaultToolkit().createImage(filteredImgProd);
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getSize().width, getSize().height);
// draw the original icon
g.drawImage(originalIcon.getImage(), 100, 10, this);
// draw the transparent icon
g.drawImage(transparentImg, 140, 10, this);
}
};
public SimpleFrame() {
super("Transparency Example");
JPanel content = (JPanel)getContentPane();
mainPanel.setBackground(Color.black);
content.add("Center", mainPanel);
}
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleFrame c = new SimpleFrame();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setSize(280,100);
c.setVisible(true);
}
});
}
}
總結(jié)
以上是生活随笔為你收集整理的java绘制半透明图片_如何使绘制的图像在Java中透明的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【ES6(2015)】String
- 下一篇: int** 赋值_关于Java语言复合赋