如何淡入/淡出 Java 图形?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3952993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:06:33  来源:igfitidea点击:

How to fade-in / fade-out a Java Graphics?

javagraphicsanimationeffects

提问by Michael Mao

Say if I have a Java Graphics object, and I want to draw a line or a rectangle on it. 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.

假设我有一个 Java Graphics 对象,我想在它上面画一条线或一个矩形。当我发出绘制命令时,它立即出现在屏幕上。我只是想知道我怎么能把这个进步作为淡入/淡出效果,就像你在 Javascript 中可以实现的那样。

Any thoughts?

有什么想法吗?

Many thanks for the help and suggestions in advance!

非常感谢您提前提供的帮助和建议!

回答by dogbane

You could try painting the image over and over again but with a different opacity (alpha) value. Start from 0 (completely transparent) and gradually increase to 1 (opaque) in order to produce a fade-in effect. Here is some test code which might help:

您可以尝试一遍又一遍地绘制图像,但使用不同的不透明度 (alpha) 值。从 0(完全透明)开始逐渐增加到 1(不透明)以产生淡入效果。这是一些可能有帮助的测试代码:

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();
    }
}

回答by Andrew Thompson

Have a look at the AlphaCompositeclass for the transparency, and the Swing based Timerclass for timing.

查看透明度的AlphaComposite类和计时的基于 Swing 的Timer类。

The Java 2D API Sample Programshas demos. under the Composite heading that show how to tie them together.

的Java 2D API样本程序有演示。在显示如何将它们联系在一起的“组合”标题下。

回答by Faisal Feroz

Take a look at the Java Timing Framework.

看一看Java 计时框架