Thursday, April 15, 2021

[Java Code Sample] Fade in and fade out image - Edit alpha channel

 

Here's a sample code to change image's opacity so image gradually appears/disappears.


Video tutorial:


Code:


import java.awt.Color;

import javax.swing.JFrame;

public class Main {

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

	}
	public Main() {
	
		JFrame window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		
		Screen screen = new Screen();
		window.add(screen);
		
		window.setVisible(true);
	};

}

(If you want to make the image gradually disappear, start the alphaValue from 1f and decrease it until it hits 0 in the actionPerformed method)


import java.awt.AlphaComposite;
import java.awt.Color;
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.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Screen extends JPanel implements ActionListener{
	
	Timer alphaTimer = new Timer(20,this);
	BufferedImage buffImage;
	
	float alphaValue = 0f;
//	float alphaValue = 1f;
		
	
	public Screen() {
		
		JLabel label = new JLabel();
		ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("backgraoundimage.png"));
		label.setIcon(icon);
		this.add(label);
		
		loadBufferedImage();
		alphaTimer.start();
		
	}
	public void loadBufferedImage() {
		
		buffImage = null;
		
		try {
			buffImage = ImageIO.read(getClass().getClassLoader().getResource("characterimage.png"));
			
		}catch(IOException e) {
			
		}
	}
	public void paint(Graphics g) {
		
		super.paint(g);
		Graphics2D g2d = (Graphics2D)g;
		
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alphaValue));		
		g2d.drawImage(buffImage, 50, 20, null);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
//		alphaValue = alphaValue -0.01f;
//		
//		if(alphaValue < 0) {
//			alphaValue = 0;
//			alphaTimer.stop();
//		}
				
		alphaValue = alphaValue +0.01f;
		
		if(alphaValue > 1) {
			alphaValue = 1;
			alphaTimer.stop();
		}
		
		repaint();		
	}
}




end

No comments:

Post a Comment