2011/05/30

Translucent image caption using JTextArea, OverlayLayout, EaseInOut

Code

private int delay = 4;
private int count = 0;

@Override public void mouseEntered(MouseEvent e) {
  if (animator != null && animator.isRunning() || yy == textArea.getPreferredSize().height) {
    return;
  }
  double h = (double) textArea.getPreferredSize().height;
  animator = new Timer(delay, new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
      double a = easeInOut(++count / h);
      yy = (int) (.5 + a * h);
      textArea.setBackground(new Color(0f, 0f, 0f, (float) (.6 * a)));
      if (yy >= textArea.getPreferredSize().height) {
        yy = textArea.getPreferredSize().height;
        animator.stop();
      }
      revalidate();
      repaint();
    }
  });
  animator.start();
}

@Override public void mouseExited(MouseEvent e) {
  if (animator != null && animator.isRunning() ||
     contains(e.getPoint()) && yy == textArea.getPreferredSize().height) return;
  double h = (double) textArea.getPreferredSize().height;
  animator = new Timer(delay, new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
      double a = easeInOut(--count / h);
      yy = (int) (.5 + a * h);
      textArea.setBackground(new Color(0f, 0f, 0f, (float) (.6 * a)));
      if (yy <= 0) {
        yy = 0;
        animator.stop();
      }
      revalidate();
      repaint();
    }
  });
  animator.start();
}

// @see Math: EaseIn EaseOut, EaseInOut and BeziƩr Curves | Anima Entertainment GmbH
// http://www.anima-entertainment.de/math-easein-easeout-easeinout-and-bezier-curves
public double easeInOut(double t) {
  // range: 0.0 <= t <= 1.0
  if (t < .5) {
    return .5 * Math.pow(t * 2d, 3d);
  } else {
    return .5 * (Math.pow(t * 2d - 2d, 3d) + 2d);
  }
}

public static double intpow(double x, int n) {
  double aux = 1d;
  if (n < 0) {
    throw new IllegalArgumentException("n must be a positive integer");
  }
  for (; n > 0; x *= x, n >>>= 1) {
    if ((n & 1) != 0) {
      aux *= x;
    }
  }
  return aux;
}

References

No comments:

Post a Comment