---
category: swing
folder: Zoom
title: MouseWheelで画像のズームイン・アウト表示
tags: [MouseWheelListener, ImageIcon, JComponent]
author: aterai
pubdate: 2006-10-16T13:11:04+09:00
description: マウスホイールなどで画像をズームイン、ズームアウトします。
image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTW1yBNHvI/AAAAAAAAAp4/ba6eQ-Ul2sg/s800/Zoom.png
---
* 概要 [#summary]
マウスホイールなどで画像をズームイン、ズームアウトします。

#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTW1yBNHvI/AAAAAAAAAp4/ba6eQ-Ul2sg/s800/Zoom.png)

* サンプルコード [#sourcecode]
#code(link){{
class ZoomImage extends JPanel {
  private transient MouseWheelListener handler;
  private final transient Image image;
  private final int iw;
  private final int ih;
  private double scale = 1d;
  protected ZoomImage(Image image) {
    super();
    this.image = image;
    iw = image.getWidth(this);
    ih = image.getHeight(this);
  }
  @Override public void updateUI() {
    removeMouseWheelListener(handler);
    super.updateUI();
    handler = e -> changeScale(e.getWheelRotation());
    addMouseWheelListener(handler);
  }
  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.scale(scale, scale);
    g2.drawImage(image, 0, 0, iw, ih, this);
    g2.dispose();
  }
  public void initScale() {
    scale = 1d;
    repaint();
  }
  public void changeScale(int iv) {
    scale = Math.max(.05, Math.min(5d, scale - iv * .05));
    repaint();
  }
}
}}

* 解説 [#explanation]
上記のサンプルでは、画像をマウスホイールの上回転で拡大、下回転で縮小して`JPanel`内に表示しています。

* 参考リンク [#reference]
- [[JPanelに表示した画像のズームとスクロール>Swing/ZoomingAndPanning]]

* コメント [#comment]
#comment
- `ih = icon.getIconWidth();`の部分は`getIconHeight();`ではありませんでしょうか? -- &user(syo); &new{2007-05-18 (金) 13:11:04};
-- ご指摘ありがとうございます。スクリーンショットもよく見たら中の画像が正方形になってますね(^^;。修正しておきます。 -- &user(aterai); &new{2007-05-18 (金) 13:25:06};

#comment