我如何淡入淡出图像?

我有一个从JPanelinheritance而来的类,我想要设置一个小animation来显示面板/图像,然后在事件触发时淡出。

我大概设置了一个线程,并开始animation,但我该怎么做,实际上做淡出?

你可以自己做线程,但是使用Trident库来处理它可能更容易。 如果你在你的类上创build了一个叫setter( setOpacity )的setter,你可以要求trident在特定的时间内将“opacity”字段从1.0增加到0.0(这里是一些关于如何使用Trident 的文档 )。

在绘制图像时,可以使用AlphaComposite的透明度,使用更新后的“不透明度”值作为组合的alpha参数。 有一个Sun教程,其中包括一个alpha复合的例子 。

这里是一个使用alpha透明度的例子。 您可以使用此复合工具查看使用不同颜色,模式和alpha的结果。

图片

 import java.awt.*; import java.awt.event.*; import java.awt.event.ActionListener; import javax.swing.*; public class AlphaTest extends JPanel implements ActionListener { private static final Font FONT = new Font("Serif", Font.PLAIN, 32); private static final String STRING = "Mothra alert!"; private static final float DELTA = -0.1f; private static final Timer timer = new Timer(100, null); private float alpha = 1f; AlphaTest() { this.setPreferredSize(new Dimension(256, 96)); this.setOpaque(true); this.setBackground(Color.black); timer.setInitialDelay(1000); timer.addActionListener(this); timer.start(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setFont(FONT); int xx = this.getWidth(); int yy = this.getHeight(); int w2 = g.getFontMetrics().stringWidth(STRING) / 2; int h2 = g.getFontMetrics().getDescent(); g2d.fillRect(0, 0, xx, yy); g2d.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_IN, alpha)); g2d.setPaint(Color.red); g2d.drawString(STRING, xx / 2 - w2, yy / 2 + h2); } @Override public void actionPerformed(ActionEvent e) { alpha += DELTA; if (alpha < 0) { alpha = 1; timer.restart(); } repaint(); } static public void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame f = new JFrame(); f.setLayout(new GridLayout(0, 1)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new AlphaTest()); f.add(new AlphaTest()); f.add(new AlphaTest()); f.pack(); f.setVisible(true); } }); } } 

这里有一些描述图像透明度的有用信息。

你的方法是这样的:

  • 定义一个Swing Timer ,每N毫秒在事件派发线程上触发一个ActionEvent
  • ActionListener添加到应该在包含ImageComponent上调用repaint()Timer
  • 重写ComponentpaintComponent(Graphics)方法来执行以下操作:
    • Graphics对象转换为Graphics2D
    • 使用setCompositeGraphics2D上设置AlphaComposite 。 这控制了透明度。
    • 绘制图像。

对于淡出animation的每一次迭代,您都可以更改AlphaComposite的值,使图像更加透明。