如何使绘制的图像在Java中透明

Nic*_*las 3 java transparency imageicon

我让动画在Snake Clone Game中运行.但基于图片的问题是图像没有透明度(注意圆形图片的白色背景.编程方面,是否有一个修复,能够包括这些绘制图像的透明度?

这是包含我的代码和程序输出的图片.

在此输入图像描述

PS在旁注中,我决定粘贴直接链接而不是IMG代码,因为我似乎无法在StackOverFlow上显示它.我在IMG代码的前面加了一个感叹号,但它没有用,所以这里是直接链接.

808*_*und 7

正如另一个答案所提到的,最简单的方法可能是简单地使用具有透明背景的PNG图像(您可以使用像GIMP这样的图像编辑器创建这些图像).或者,如果您仅限于具有纯色背景的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);
         }
      });
   }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

请勿使用油漆绘制图像。使用其他使用alpha的程序,如Paint.net或Photoshop ...如果要永久使用圆圈,则可以使用g.drawOval(x,y,w,h)。