Oak
Oak

Reputation: 518

Java - Image Transparency With Graphics g

I would like to create a fade in and fade out effect for one of the characters in my video game. To do this I would like to have the image of them be fade out and fade back in. I would like to change the opacity of the image but have no idea how. I am using the java Graphics. Here is some code.

g.drawImage(joople, jx, jy, sx, sy, this);

I am running this code in this method:

public void paint(Graphics g) {

Many thanks, Oak

Upvotes: 0

Views: 1925

Answers (2)

KDDZ - SF Engineer
KDDZ - SF Engineer

Reputation: 7

This is a easy and short most developers using java code for image fade.

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 *
 * @author ADMIN
 */
public class ImageFade extends JFrame {

    ImageFade() {
        setLayout(null);

        JLabel l = new JLabel();
        l.setBounds(0, 0, 100, 96);
        add(l);

        Thread tp = new Thread() {
            @Override
            public void run() {
                for (int amp = 0; amp <= 500; amp++) {
                    try {
                        sleep(1);
                        try {
                            BufferedImage bim = ImageIO.read(new File("src/image/fade/image.png"));
                            BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);
                            Graphics2D createGraphics = nbim.createGraphics();
                            createGraphics.drawImage(bim, null, 0, 0);
                            RescaleOp r = new RescaleOp(new float[]{1f, 1f, 1f, (float) amp / 500}, new float[]{0, 0, 0, 0}, null);
                            BufferedImage filter = r.filter(nbim, null);
                            l.setIcon(new ImageIcon(filter));
                        } catch (Exception ex) {
                            System.err.println(ex);
                        }
                    } catch (InterruptedException ex) {
                    }
                }
            }
        };
        tp.start();

        setUndecorated(true);
        setBackground(new Color(0, 0, 0, 0));
        setSize(100, 96);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setAlwaysOnTop(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ImageFade fr = new ImageFade();
    }
}

in this code you can see a thread code. in the thread this image will fade in.

the used image is stack overflow web page's logo image.

only by shown code the image will fade in.

Thread tp = new Thread() {
    @Override
    public void run() {
        for (int amp = 0; amp <= 500; amp++) {
            try {
                sleep(1);
                try {
                    BufferedImage bim = ImageIO.read(new File("src/image/fade/image.png"));
                    BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);
                    Graphics2D createGraphics = nbim.createGraphics();
                    createGraphics.drawImage(bim, null, 0, 0);
                    RescaleOp r = new RescaleOp(new float[]{1f, 1f, 1f, (float) amp / 500}, new float[]{0, 0, 0, 0}, null);
                    BufferedImage filter = r.filter(nbim, null);
                    l.setIcon(new ImageIcon(filter));
                } catch (Exception ex) {
                      System.err.println(ex);
                  }
            } catch (InterruptedException ex) {
            }
        }
    }
};
tp.start();

This code is very simple to use.

This is not from any book, internet or etc. It is developed by me.

A normal image is not able to change alpha. By code : BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB); the image will convert to ARGB - Alpha, Red, Green, Blue (R,G,B,A) image.

So you can change the alpha of a image.

From this code your image will show smoothly more than answer 1's code user's.

Upvotes: -1

MadProgrammer
MadProgrammer

Reputation: 347184

You will want to have a look at Compositing Graphics

enter image description here

import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class FadeMe {

    public static void main(String[] args) {
        new FadeMe();
    }

    public FadeMe() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage img;
        private float alpha = 0;
        private float delta = 0.01f;

        public TestPane() {
            try {
                img = ImageIO.read(...);
                Timer timer = new Timer(40, new ActionListener(){ 
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        alpha += delta;
                        if (alpha > 1.0) {
                            alpha = 1.0f;
                            delta *= -1.0f;
                        } else if (alpha < 0.0) {
                            alpha = 0.0f;
                            delta *= -1.0f;
                        }
                        repaint();
                    }
                });
                timer.start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img != null ? new Dimension(img.getWidth(), img.getHeight()) : new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
            int x = (getWidth() - img.getWidth()) / 2;
            int y = (getHeight() - img.getHeight()) / 2;
            g2d.drawImage(img, x, y, this);
            g2d.dispose();
        }

    }

}

Upvotes: 4

Related Questions