简体   繁体   English

在Java 2d / AWT中淡出效果

[英]Fade out effect in Java 2d/AWT

I would like to display an image for 6.5s in total and fade it out in the last 1.5s. 我想显示总共6.5s的图像,并在最后1.5s内将其淡出。 I'm getting a NPE at line: 我在网上得到了NPE:

g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));

I read some, and I think it is because gameLogo is not a BufferedImage, just a simple Image. 我读了一些,我认为是因为gameLogo不是BufferedImage,而只是一个简单的Image。 I made it with paint.net so it should have an alpha channel by default. 我是用paint.net制作的,因此默认情况下应该具有Alpha通道。 I searched some forums about making BufferedImage but still confused. 我搜索了一些有关制作BufferedImage的论坛,但仍然感到困惑。

The code snippet below worked perfectly before I added the extra lines to chage the last 1.5s. 在我添加额外的行以抵消最后的1.5秒之前,下面的代码段运行良好。

Thank you for your help in advance! 提前谢谢你的帮助!

EDIT: 编辑:

with adding cast (Graphics2D) NPE if fixed but it still doesn't fade out totally... 如果已修复,则添加强制转换(Graphics2D)NPE,但它仍不会完全消失...

Should I use offG.dispose(); 我应该使用offG.dispose();吗? somewhere? 某处?

offG.setColor(Color.BLACK);
offG.fillRect(0, 0, 800, 480);
counter += deltaTime;
// start fade out after 4 seconds
if (counter < 4000)
    offG.drawImage(devLogo, 0, 0, this);
else {
    transparency = (float)(1 - (counter - 4000) / 50 * 0.02);
    if (transparency < 0)
    transparency = 0;
    ((Graphics2D) offG).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));
    offG.drawImage(devLogo, 0, 0, this);
}
// wait 6,5 seconds
if (counter > 6500) {
    gameState = 2;
    counter = 0;
    transparency = 1;
    ((Graphics2D) offG).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));
}

You should provide more code for that. 您应该为此提供更多代码。 In you case g2d is null . 在您的情况下, g2dnull According to your comment you are holding Graphics objects in fields. 根据您的评论,您将在字段中保存Graphics对象。 Graphics object is passed to the drawing method by AWT, and you probably assigning it to your field, but you forgot to assign new value to your g2d field as well. Graphics对象由AWT传递给绘图方法,您可能已将其分配给字段,但是您忘记了也为g2d字段分配了新值。 I think there is no need to keep single object in 2 different typed fields. 我认为没有必要在2个不同类型的字段中保留单个对象。 If I were you I would operate only on Graphics2d type object. 如果您是我,我将只对Graphics2d类型的对象进行操作。 That would put end to the confusion in your code that you have made. 这将消除您在代码中造成的混乱。 You are threating the same Graphics object as 2 separate entities but your fields referring to the same object. 您威胁到与2个独立实体相同的Graphics对象,但您的字段引用的是同一对象。 Why for? 为什么? No need for that. 没必要。

  ((Graphics2d)offG).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));

and NPE is gone right? NPE没事了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM