概要

RandomDissolve効果で表示する画像を切り替えます。

サンプルコード

class RandomDissolve extends JComponent implements ActionListener {
  private static final int STAGES = 16;
  private final Random rnd = new Random();
  private final Timer animator;
  private final transient BufferedImage image1;
  private final transient BufferedImage image2;
  private transient BufferedImage buf;
  private boolean mode = true;
  private int currentStage;
  private int[] src;
  private int[] dst;
  private int[] step;

  protected RandomDissolve(BufferedImage i1, BufferedImage i2) {
    super();
    this.image1 = i1;
    this.image2 = i2;
    this.buf = copyImage(mode ? image2 : image1);
    animator = new Timer(50, this);
  }

  private boolean nextStage() {
    return currentStage > 0 && copyNextStage();
  }

  @SuppressWarnings("PMD.AvoidArrayLoops")
  private boolean copyNextStage() {
    currentStage -= 1;
    for (int i = 0; i < step.length; i++) {
      if (step[i] == currentStage) {
        src[i] = dst[i];
      }
    }
    return true;
  }

  private static BufferedImage copyImage(BufferedImage image) {
    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = result.createGraphics();
    g2.drawRenderedImage(image, null);
    g2.dispose();
    return result;
  }

  private static int[] getData(BufferedImage image) {
    WritableRaster wr = image.getRaster();
    DataBufferInt dbi = (DataBufferInt) wr.getDataBuffer();
    return dbi.getData();
    // return ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
  }

  public void animationStart() {
    currentStage = STAGES;
    buf = copyImage(mode ? image2 : image1);
    src = getData(buf);
    dst = getData(copyImage(mode ? image1 : image2));
    step = new int[src.length];
    mode ^= true;
    for (int i = 0; i < step.length; i++) {
      step[i] = rnd.nextInt(currentStage);
    }
    animator.start();
  }

  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setPaint(getBackground());
    g2.fillRect(0, 0, getWidth(), getHeight());
    g2.drawImage(buf, 0, 0, buf.getWidth(), buf.getHeight(), this);
    g2.dispose();
  }

  @Override public void actionPerformed(ActionEvent e) {
    if (nextStage()) {
      repaint();
    } else {
      animator.stop();
    }
  }
}
View in GitHub: Java, Kotlin

解説

  • BufferedImageからWritableRasterを取得し、元画像と次の画像のコピーからint配列をそれぞれ作成
  • 元画像の配列を次の画像のピクセルでランダムに置き換えて再描画することで画像の切り替えを実行

参考リンク

コメント