memorandums

日々の生活で問題解決したこと、知ってよかったことなどを自分が思い出すために記録しています。

クリッピングつきイメージスクロール

あるソフトのプロトタイプをProcessingで作っていてタイトルのような機能が必要になりました。それらしい既存ライブラリが無かったので作りました。プログラムはベタですが。。。とりあえず動きます。イベント処理もクラスの中でやってしまった方がいいのでしょうけど、全体のイベント処理を他でやりたいのでこのような、ある意味中途半端なクラスになっています。よければ使ってみてください。以下がリストです。その下にpdeファイルをおいておきました。

■ScrollableImage

class ScrollableImage
{
  PImage src;
  PGraphics pg;
  int x, y, dx, dy;
  int width, height;
  int left_margin, top_margin;
  
  public ScrollableImage(PImage img, int left_margin, int top_margin, int width, int height) {
    this.left_margin = left_margin;
    this.top_margin = top_margin;
    this.width = width;
    this.height = height;
    src = img;
    pg = createGraphics(width, height, P2D);
    x = this.width / 2;
    y = this.height / 2;
  }
  
  public void update(int dx, int dy) {
    if (dx != 0 || dy != 0) {
      x += dx;
      y += dy;
      x = constrain(x + dx, 0, src.width - pg.width);
      y = constrain(y + dy, 0, src.height - pg.height);
      pg.copy(src, x, y, pg.width, pg.height, 0, 0, pg.width, pg.height);
    }
  }
  
  public void draw() {
    image(pg, top_margin, left_margin);
  }
}

■テストクラス

ScrollableImage si;

void setup() {
  size(300, 300);
  si = new ScrollableImage(loadImage("map.png"), 20, 20, 260, 260);
}

void draw() {
  if (mousePressed) si.update(pmouseX - mouseX, pmouseY - mouseY);
  si.draw();
}

Link: test_ScrollableImage