TITLE:Iconを回転する

Posted by aterai at 2012-06-11

Iconを回転する

画像ファイルから90、180、270度回転したIconを作成します。

  • &jnlp;
  • &jar;
  • &zip;
RotatedIcon.png

サンプルコード

class RotateIcon implements Icon {
  private int width, height;
  private Image image;
  private AffineTransform trans;
  public RotateIcon(Icon icon, int rotate) {
    image = new BufferedImage(
      icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    icon.paintIcon(null, g, 0, 0);
    g.dispose();

    width  = icon.getIconWidth();
    height = icon.getIconHeight();
    if((rotate+360)%360==90) {
      trans = AffineTransform.getTranslateInstance(height, 0);
      trans.rotate(Math.toRadians(90));
    }else if((rotate+360)%360==270) {
      trans = AffineTransform.getTranslateInstance(0, width);
      trans.rotate(Math.toRadians(270));
    }else if((rotate+360)%360==180) {
      //trans = AffineTransform.getTranslateInstance(width, height);
      //trans.rotate(Math.toRadians(180));
      trans = AffineTransform.getScaleInstance(1.0, -1.0);
      trans.translate(0, -height);
      width  = icon.getIconHeight();
      height = icon.getIconWidth();
    }else{
      throw new IllegalArgumentException("Rotate must be (rotate % 90 == 0)");
    }
  }
  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D)g.create();
    g2.translate(x, y);
    g2.drawImage(image, trans, c);
    g2.translate(-x, -y);
    g2.dispose();
  }
  @Override public int getIconWidth()  {
    return height;
  }
  @Override public int getIconHeight() {
    return width;
  }
}

解説

  • Default
    • 幅高さ: 83x100
  • Rotate: 180
  • Rotate: 90(時計回りに90度)
    • 幅高さ: 100x83(元画像の幅高さを入れ替え)
    • 左上を原点に90度回転し、元画像の高さだけX軸プラス方向に移動
  • Rotate: -90(反時計回りに90度)
    • 幅高さ: 100x83(元画像の幅高さを入れ替え)
    • 左上を原点に270度回転し、元画像の幅だけY軸プラス方向に移動

参考リンク

コメント