【问题标题】:transparent .png background透明.png背景
【发布时间】:2013-12-10 21:51:35
【问题描述】:

我知道我不是第一个提出此类问题的人,但我认为我的问题有点不同。

我有一个我在播放器的 MS Paint 上绘制的 png 图像,当我使用图形对象绘制图像时,我希望图像的背景是透明的。我尝试了一些魔法粉红色的东西,但它在 java 中的工作似乎不一样。我不是java新手,但是我没有经验,所以你能解释一下你使用的任何包或方法吗?谢谢!

【问题讨论】:

  • 背景图和播放器图是两个不同的图吗?
  • 是的,我有一块地砖,然后我在上面画了玩家图像,这样你就可以看到他周围的地板了。
  • 在下面给出了答案。检查

标签: java png transparency


【解决方案1】:
  1. 您需要使用AlphaComposite 来获得透明效果:
  2. 假设您已经知道Graphics2DGraphics 使用BufferedImage
  3. 创建临时图形对象g.create(),然后处理该对象,以便安全恢复对象创建后更改的图形对象状态。

    protected void paintComponent(Graphics g) {
        super.paintComponent(g); 
    
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
        g2d.drawImage(tileImage, 0, 0, getWidth(), getHeight());
        g2d.dispose();
    
        // draw player image
    
    } 
    

【讨论】:

  • setcomposite() 和 derived() 方法有什么作用?
  • Graphics2D.setComposite 设置我们传入的复合材料。AlphaComposite.SrcOver.derive(alpha) 返回一个类似的使用指定 alpha 值的 AlphaComposite 对象。我添加了 Class 文档的链接。详情请查看
【解决方案2】:

对于 Java6,TrayIcon 应使用 PNG 图片,但如此 SO 问题中所述,请检查:

the background color chosen to represent the transparent pixels
the transparency options
the resolution of the icon
alternate format like SVG (provided you are using external library like Batik, and     
conversion mechnism to java.awt.Image)

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 1970-01-01
    • 2015-06-22
    • 2015-04-20
    • 2014-12-18
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    相关资源
    最近更新 更多