简体   繁体   English

如何淡入/淡出Java图形?

[英]How to fade-in / fade-out a Java Graphics?

Say if I have a Java Graphics object, and I want to draw a line or a rectangle on it. 假设我有一个Java Graphics对象,我想在其上绘制一条线或一个矩形。 When I issue the command to draw, it appears on screen immediately. 当我发出绘制命令时,它立即出现在屏幕上。 I just wonder how could I make this progress as a fade-in / fade-out effect, same as what you can achieve in Javascript. 我只是想知道如何将这个进步作为淡入/淡出效果,就像你在Javascript中可以实现的那样。

Any thoughts? 有什么想法吗?

Many thanks for the help and suggestions in advance! 非常感谢您提前提供的帮助和建议!

You could try painting the image over and over again but with a different opacity (alpha) value. 您可以尝试反复绘制图像,但使用不同的不透明度(alpha)值。 Start from 0 (completely transparent) and gradually increase to 1 (opaque) in order to produce a fade-in effect. 从0开始(完全透明)并逐渐增加到1(不透明)以产生淡入效果。 Here is some test code which might help: 以下是一些可能有用的测试代码:

float alpha = 0.0f;

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    //set the opacity
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, alpha));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    //do the drawing here
    g2d.drawLine(10, 10, 110, 110);
    g2d.drawRect(10, 10, 100, 100);

    //increase the opacity and repaint
    alpha += 0.05f;
    if (alpha >= 1.0f) {
        alpha = 1.0f;
    } else {
        repaint();
    }

    //sleep for a bit
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
}

Have a look at the AlphaComposite class for the transparency, and the Swing based Timer class for timing. 看看AlphaComposite类的透明度,以及基于Swing的Timer类的时序。

The Java 2D API Sample Programs has demos. Java 2D API示例程序具有演示。 under the Composite heading that show how to tie them together. 在Composite标题下显示如何将它们绑在一起。

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

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