3
\$\begingroup\$

Hello I have a game where you feed animals. A few minutes after you feed them they do a poo. I want the poo to fade away after a few seconds. I want to know how to change the opacity on the image. How can I do this?

here is my code:

package items;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class poo {

    public int x, y;
    private Image img;

    public int time = 0;
    public int timer = 100;
    public boolean remove;

    public float alpha = 1f;

    public poo(int x, int y) {
        this.x = x;
        this.y = y;

        alpha = 1f;
    }

    public void tick() {
        if (time >= timer) {
            time = 0;
            // remove = true;
        } else {
            time++;
        }
        if (alpha > 2) {
            // alpha--;
        } else {
            // remove = true;
        }

    }

    public void render(Graphics g) {

        ImageIcon i2 = new ImageIcon("res/items/poo.png");
        img = i2.getImage();

        g.drawImage(img, x, y,6,8, null);


    }
}
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

You could use an AlphaComposite to draw your Image transparently on top of what you have already drawn.

//...
float alpha = 0.5 //draw half transparent
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,alpha);
g.setComposite(ac);
//g.drawimage...

Here is a question with a similar topic: https://stackoverflow.com/questions/17731576/making-an-image-fade-in-and-fade-out/17731785#17731785

And this is the official help topic from oracle, that explains the blend modes: https://docs.oracle.com/javase/tutorial/2d/advanced/compositing.html

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .