SoFunction
Updated on 2025-05-18

Java implements image fading effect

Java implements image fading effect

Updated: May 18, 2025 11:52:28 Author: Katie.
In modern graphical user interface and game development, **Picture Fade In/Out** is a common and practical visual transition effect. It can be used for scenes such as launch screen, scene switching, carousel pictures, prompt box pop-ups, etc. Through this project, you will have a comprehensive understanding of the key points of achieving fade in Java. Friends who need it can refer to it.

1. Detailed introduction to the project background

In modern graphical user interfaces and game development, Fade In/Out is a common and practical visual transition effect. It can be used for scenes such as launch screen, scene switching, carousel images, prompt box pop-up, etc. By controlling the smooth change of image transparency between 0 and 1, creating an elegant visual experience. For beginners, mastering this effect helps to understand core technologies such as graphics rendering, timer driving and hybrid mode; for engineering projects, encapsulating the fade effect into reusable components can greatly improve the interface quality and user experience.

This project is based on the Java platform and is provided separatelySwing+Java2DandJavaFXTwo implementation plans, and focus on explaining:

  • Transparency rendering principle:Alpha mixed withComposite/BlendModeuse;

  • Time-driven mechanismandAnimationTimerThe differences and advantages;

  • Easing function: Application of linear, secondary, tertiary, tertiary and other easing algorithms;

  • Component packaging: Interface-oriented design to realize configurable and easy-to-ext fade components;

  • Performance optimization: Double buffering, off-screen cache and minimum redraw area;

  • Event callback: Animation life cycle management and external interaction;

Through this project, you will have a comprehensive understanding of the key points of achieving fade effects in Java, and be able to quickly integrate and develop secondary in your own applications.

2. Detailed introduction to project requirements

2.1 Functional Requirements

  1. Basically fade in and out

    • Fade from completely transparent (alpha=0) to completely opaque (alpha=1);

    • Return from total opaque to completely transparent fade out;

  2. Two-way control

    • The same component can be executable fade in or out;

  3. Duration can be configured

    • Supports any duration from tens of milliseconds to several seconds;

  4. Easing algorithm is optional

    • Linear, Quad, Cubic, Sine, etc.;

  5. Loop and overlay

    • Supports automatic cycle fading in and out, or staying after fading in and after fading out;

  6. Event callback

    • Callbacks can be registered when the animation starts, updates each frame, and the animation is completed;

  7. Midway control

    • supportpause()resume()stop(), and can adjust the duration and mode during operation;

  8. Multiple instance support

    • The same interface can perform independent animations on multiple picture components at the same time;

  9. Resource loading

    • Preload pictures asynchronously to avoid lag at the beginning of the animation;

2.2 Non-functional requirements

  • performance: Execute smoothly under 60 FPS conditions to avoid frame skipping or lag;

  • Maintainability: Modular code, complete annotations, and provide unit tests;

  • Scalability: Open interface, supports custom blending mode or multi-layer blending;

  • portability: Pure Java implementation, compatible with Java 8+;

  • stability: Catch exceptions and provide downgrade logic to ensure that the UI does not crash due to animation exceptions;

3. Detailed introduction to related technologies

3.1 Java2D Mixing and Transparency

  • use((AlphaComposite.SRC_OVER, alpha))

  • AlphaComposite.SRC_OVERIn mode, the source image and the target image are mixed according to the alpha value.

  • Off-screenBufferedImageCache to improve repeated drawing performance

3.2 Swing timer

  • Trigger on Event Dispatch Thread (EDT)ActionListener

  • Suitable for GUI animations, need to cooperaterepaint()Implement frame refresh

  • Note EDT blocking and long time-consuming operation problems

3.3 JavaFX rendering pipeline

  • AnimationTimerCalled per framehandle(long now), nanosecond accuracy

  • Canvas + GraphicsContextProvide pixel-level drawing

  • ()The node transparency can be directly manipulated, but the easing function cannot be customized

3.4 Easing function

  • Linear: uniform transition

  • Quad:t*tort*(2-t)

  • Three times (Cubic), Sine, Elastic, etc.

  • Common formulas and implementations

3.5 Performance optimization

  • Double buffering: Swing default double buffering, JavaFX Canvas optional

  • Partial redraw:repaint(x,y,w,h)Only redraw the changing area

  • Cache animated frames: pre-calculate several keyframe maps

4. Detailed introduction to the implementation ideas

  1. Interface abstraction

    • DefinitionFadeAnimationInterface:fadeIn()fadeOut()pause()resume()setDuration()setEasing()addListener()

  2. Swing implementation

    • SwingFadeLabelInheritanceJLabelorJComponent, holdBufferedImage

    • Internal useDriver, calculate per framealphaandrepaint()

    • existpaintComponentSettingsAlphaCompositeand draw pictures;

  3. JavaFX implementation

    • FxFadeImageViewbased onImageView,controlopacityAttributes;

    • useAnimationTimerorTimeline, update according to time incrementopacity

    • Available inCanvasManually draw and set global alpha;

  4. Easing integration

    • Abstract the easing function asEasingFunctionInterface;

    • Based on progress in animation drivertcalculate(t)

  5. Lifecycle Management

    • Animation state machine:READY → RUNNING → PAUSED → COMPLETED

    • Triggered when the state changesonStartonPauseonCompleteCallback

  6. Multiple instances & managers

    • FadeManagerRegister all animation instances, start/stop/global pause in a unified manner;

  7. Asynchronous loading

    • useSwingWorkerorTaskAsynchronous loadingBufferedImage, automatically after loadingfadeIn()

  8. Tests and Examples

    • Provide sample code to show the effects of different easing and duration parameters;

    • Unit test verification alpha calculation accuracy and boundary conditions

5. Complete implementation of the code

// =====  =====
<project xmlns="/POM/4.0.0" …>
  <modelVersion>4.0.0</modelVersion>
  <groupId></groupId>
  <artifactId>fade-animation</artifactId>
  <version>1.0.0</version>
</project>
 
// ===== src/main/java/com/example/fade/ =====
package ;
 
/** Easing function interface */
public interface EasingFunction {
    /** @param t Progress [0,1], @return eased Progress */
    double apply(double t);
}
 
// ===== src/main/java/com/example/fade/ =====
package ;
 
/** Commonly used easing function implementation */
public class Easings {
    public static final EasingFunction LINEAR = t -> t;
    public static final EasingFunction EASE_IN_QUAD = t -> t * t;
    public static final EasingFunction EASE_OUT_QUAD = t -> t * (2 - t);
    public static final EasingFunction EASE_IN_OUT_CUBIC = t ->
        t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2, 3) / 2;
    // More...}
 
// ===== src/main/java/com/example/fade/ =====
package ;
 
/** Animation monitor */
public interface FadeListener {
    void onStart();
    void onFrame(double progress);
    void onPause();
    void onResume();
    void onComplete();
}
 
// ===== src/main/java/com/example/fade/ =====
package ;
 
public interface FadeAnimation {
    void fadeIn();
    void fadeOut();
    void pause();
    void resume();
    void stop();
    void setDuration(long millis);
    void setEasing(EasingFunction easing);
    void addListener(FadeListener listener);
    boolean isRunning();
}
 
// ===== src/main/java/com/example/fade/ =====
package ;
 
import .*;
import .*;
import .*;
import ;
import ;
import ;
 
/**
  * Fade-in and out components implemented by Swing, inheriting JLabel
  */
public class SwingFadeLabel extends JLabel implements FadeAnimation {
    private BufferedImage image;
    private long duration = 1000;
    private EasingFunction easing = ;
    private  timer;
    private long startTime;
    private boolean fadeInMode;
    private List<FadeListener> listeners = new ArrayList<>();
 
    public SwingFadeLabel(BufferedImage img) {
         = img;
        setPreferredSize(new Dimension((), ()));
        setOpaque(false);
        initTimer();
    }
 
    private void initTimer() {
        timer = new (16, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                long now = ();
                double t = (now - startTime) / (double) duration;
                if (t >= 1) t = 1;
                double progress = (fadeInMode ? t : (1 - t));
                for (FadeListener l : listeners) (progress);
                repaint();
                if (t >= 1) {
                    ();
                    for (FadeListener l : listeners) {
                        if (fadeInMode) (); else ();
                    }
                }
            }
        });
    }
 
    @Override protected void paintComponent(Graphics g) {
        (g);
        Graphics2D g2 = (Graphics2D) ();
        float alpha = 1f;
        if (()) {
            long now = ();
            double t = (now - startTime) / (double) duration;
            if (t > 1) t = 1;
            alpha = (float) (fadeInMode ? (t) : (1 - t));
        }
        ((AlphaComposite.SRC_OVER, alpha));
        (image, 0, 0, null);
        ();
    }
 
    @Override public void fadeIn() {
        fadeInMode = true; startTime = ();
        for (FadeListener l : listeners) (); ();
    }
    @Override public void fadeOut() {
        fadeInMode = false; startTime = ();
        for (FadeListener l : listeners) (); ();
    }
    @Override public void pause() { (); (FadeListener::onPause); }
    @Override public void resume() { startTime = () - (long)(duration * getCurrentProgress()); (); (FadeListener::onResume); }
    @Override public void stop() { (); (FadeListener::onComplete); }
    @Override public void setDuration(long millis) {  = millis; }
    @Override public void setEasing(EasingFunction easing) {  = easing; }
    @Override public void addListener(FadeListener listener) { (listener); }
    @Override public boolean isRunning() { return (); }
 
    private double getCurrentProgress() {
        long now = ();
        double t = (now - startTime) / (double) duration;
        if (t < 0) t = 0; if (t > 1) t = 1;
        return (fadeInMode ? t : (1 - t));
    }
}
 
// ===== src/main/java/com/example/fade/ =====
package ;
 
import ;
import ;
import ;
import ;
import ;
 
/**
  * Fade-in and out component implemented by JavaFX, based on ImageView
  */
public class FxFadeImageView extends ImageView implements FadeAnimation {
    private long duration = 1000_000_000; // Nanoseconds    private EasingFunction easing = ;
    private List<FadeListener> listeners = new ArrayList<>();
    private AnimationTimer timer;
    private long startTime;
    private boolean fadeInMode;
 
    public FxFadeImageView(Image img) {
        super(img);
        initAnimation();
    }
 
    private void initAnimation() {
        timer = new AnimationTimer() {
            @Override public void handle(long now) {
                double t = (now - startTime) / (double) duration;
                if (t >= 1) t = 1;
                double p = (fadeInMode ? t : (1 - t));
                setOpacity(p);
                (l -> (p));
                if (t >= 1) {
                    stop();
                    (FadeListener::onComplete);
                }
            }
        };
    }
 
    @Override public void fadeIn() {
        fadeInMode = true; startTime = ();
        (FadeListener::onStart); ();
    }
    @Override public void fadeOut() {
        fadeInMode = false; startTime = ();
        (FadeListener::onStart); ();
    }
    @Override public void pause() { (); (FadeListener::onPause); }
    @Override public void resume() { startTime = () - (long)(duration * getCurrentProgress()); (); (FadeListener::onResume); }
    @Override public void stop() { (); (FadeListener::onComplete); }
    @Override public void setDuration(long ms) {  = ms * 1_000_000L; }
    @Override public void setEasing(EasingFunction easing) {  = easing; }
    @Override public void addListener(FadeListener listener) { (listener); }
    @Override public boolean isRunning() { return timer != null; }
 
    private double getCurrentProgress() {
        double t = (() - startTime) / (double) duration;
        if (t < 0) t = 0; if (t > 1) t = 1;
        return (fadeInMode ? t : (1 - t));
    }
}
 
// ===== src/main/java/com/example/ui/ =====
package ;
 
import .*;
import ;
import .*;
import ;
import ;
 
/** Swing Demo */
public class SwingDemo {
    public static void main(String[] args) throws Exception {
        BufferedImage img = (new File(""));
        SwingFadeLabel fadeLabel = new SwingFadeLabel(img);
        (2000);
        (Easings.EASE_IN_OUT_CUBIC);
        (new FadeListener() {
            public void onStart()   { ("Swing Start"); }
            public void onFrame(double p) { /* Update progress bar */ }
            public void onPause()   { ("Swing Pause"); }
            public void onResume()  { ("Swing Resume"); }
            public void onComplete(){ ("Swing Complete"); }
        });
 
        JFrame f = new JFrame("Swing Fade In Example");
        (JFrame.EXIT_ON_CLOSE);
        ().add(fadeLabel);
        (); (null); (true);
        ();
    }
}
 
// ===== src/main/java/com/example/ui/ =====
package ;
 
import .*;
import ;
import ;
import ;
import ;
 
/** JavaFX Demo */
public class FxDemo extends Application {
    @Override public void start(Stage stage) throws Exception {
        Image img = new Image("file:");
        FxFadeImageView fadeView = new FxFadeImageView(img);
        (2000);
        (Easings.EASE_OUT_QUAD);
        (new FadeListener() {
            public void onStart()   { ("FX Start"); }
            public void onFrame(double p) { /* Update UI */ }
            public void onPause()   { ("FX Pause"); }
            public void onResume()  { ("FX Resume"); }
            public void onComplete(){ ("FX Complete"); }
        });
 
        Scene scene = new Scene(new StackPane(fadeView), (), ());
        ("JavaFX Fade In Example");
        (scene); ();
        ();
    }
    public static void main(String[] args){ launch(); }
}

6. Detailed interpretation of the code

  • EasingFunction / Easings: Define and implement common easing functions to control animation progress curves;

  • FadeListener: Animation life cycle callback interface, including start, each frame, pause, resume, and completion;

  • FadeAnimation interface: Abstract fade function, including duration, easing settings and event monitoring;

  • SwingFadeLabel: Based on SwingJLabelExtend, useDrive transparency changes and inpaintComponentPassedAlphaCompositeDraw images in blend mode;

  • FxFadeImageView: JavaFX version, inheritanceImageView,useAnimationTimerUpdated per frameopacityProperties and callback listeners;

  • SwingDemo / FxDemo: Demonstrate how to load pictures, configure animation duration and easing functions, register listeners and start fade-in effects.

7. Project detailed summary

This project provides a completeJava picture fades in and outComponent solutions, covering:

  • Cross-frame compatibility: Swing and JavaFX dual version implementation

  • Configurability: Flexible and adjustable duration, easing function, loop mode and callback

  • Performance optimization: Double buffering, local redrawing and off-screen cache ensure high frame rate

  • Modular design: Separate interface and implementation, facilitate secondary expansion and testing

  • Ease of use: Simple API, a few lines of code can be integrated into the project

8. Project FAQs and Answers

Q1: Transparency jitter or uneven?
A: Check the timer interval and time increment calculation to ensure that the progress is driven using the nanosecond/millisecond difference.

Q2: Is SwingFadeLabel stuck when repainting?
A: The image can be pre-scaled and cached in long images or large resolutions, or only redraws the changing area.

Q3: JavaFX version cannot respond to pause/resume?
A: Confirmpause()Called(),existresume()Re-adjustmentstartTimeand()

9. Expansion direction and performance optimization

  1. Loop fade in and out: Automatically fade out and play it loop after fading in is completed;

  2. Multi-layer blending: Supports layering of multiple images to fade in and out at the same time to form superimposed special effects;

  3. Customize BlendMode: Used in JavaFXBlendModeAchieve a richer hybrid model;

  4. GPU acceleration: Introduce OpenGL (JOGL) rendering in Swing, or use JavaFX directly to take advantage of hardware acceleration;

  5. Keyframe animation: Extended to keyframe sequence animation, supporting composite effects such as translation, rotation, and scaling;

  6. Mobile porting: Migrate logic to Android platform and useCanvasandValueAnimatoraccomplish.

The above is the detailed content of Java's image fading effect. For more information about Java's image fading, please pay attention to my other related articles!

  • Java
  • picture
  • fade in
  • fade out

Related Articles

  • 6 super simple ways to prevent repeated data submission in Java

    In normal development, if the Internet speed is relatively slow, after the user submits the form, he finds that the server has not responded for a long time, then the user may think that he has not submitted the form, and will click the submit button to submit the form repeatedly. This article mainly introduces 6 super simple methods to prevent repeated submission of data in Java. Friends who need it can refer to it.
    2021-11-11
  • A useful widget in the Spring Framework explains the Spring Retry component

    Spring Retry is a function independent from Spring batch. It mainly implements retry and circuit breaker. For those operations that do not change the result after retry and are meaningless, it is not recommended to use retry. Today, this article will introduce you to the detailed explanation of Spring Retry components. Interested friends can take a look.
    2021-07-07
  • SWT (JFace) experience by Slider, Scale

    Slider, Scale implementation code for SWT (JFace) experience.
    2009-06-06
  • How does idea resolve maven dependency conflict

    This article mainly introduces how idea can resolve maven dependency conflict problem, which is of great reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.
    2023-12-12
  • Java implements multi-threaded web server instance based on NIO

    In this article, the editor will sort out the content of Java implementation of NIO-based multi-threaded web server examples. Friends who need it can learn it.
    2020-03-03
  • SpringBoot implements License authentication (only validation period) detailed process

    License is a copyright license certificate, which is generally used for access license certificates provided by paid software to paying users. This article mainly introduces SpringBoot to implement License authentication (only verification of validity period). Friends who need it can refer to it.
    2024-04-04
  • Incompatible areas after SpringBoot upgrade to 2.7.18 and solutions

    This article mainly introduces the incompatible areas and solutions after SpringBoot upgraded to 2.7.18. It has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.
    2024-08-08
  • Maven's implementation of direct dependency, indirect dependency, dependency conflict, dependency arbitration

    This article mainly introduces the implementation of Maven's direct dependency, indirect dependency, dependency conflict, and dependency arbitration. The article introduces the example code in detail, which has certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.
    2023-09-09
  • Java implements screenshots and cropping

    This is an entry-level article, please skip it by experts. In this article we will learn how to cut images in Java and save the cut parts to a file separately.
    2014-09-09
  • Understanding of the() function in the doFilter of Java filter

    This article mainly introduces the understanding of the() function in the Java filter doFilter, which is of good reference value and hopes to be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2021-11-11

Latest Comments