如何淡入/淡出 Java 图形?

发布于 2024-09-27 15:35:09 字数 159 浏览 3 评论 0原文

假设我有一个 Java Graphics 对象,并且我想在其上绘制一条线或一个矩形。当我发出绘图命令时,它立即出现在屏幕上。我只是想知道如何才能以淡入/淡出效果来实现这一进步,与在 Javascript 中实现的效果相同。

有什么想法吗?

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

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.

Any thoughts?

Many thanks for the help and suggestions in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冰之心 2024-10-04 15:35:09

您可以尝试一遍又一遍地绘制图像,但使用不同的不透明度(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();
    }
}

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:

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();
    }
}
最美不过初阳 2024-10-04 15:35:09

查看 AlphaComposite 类透明度,以及基于 Swing 的 Timer 类定时。

Java 2D API 示例程序 有演示。在“复合”标题下,显示如何将它们结合在一起。

Have a look at the AlphaComposite class for the transparency, and the Swing based Timer class for timing.

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

无畏 2024-10-04 15:35:09

Take a look at the Java Timing Framework.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文