TITLE:FlatteningPathIteratorでShape上の点を取得する
#navi(../)
#tags(Shape, PathIterator, FlatteningPathIterator)
RIGHT:Posted by &author(aterai); at 2013-07-08
* FlatteningPathIteratorでShape上の点を取得する [#wfe285d1]
`FlatteningPathIterator`を使って平坦化された`Shape`上の座標点を取得、描画します。

- &jnlp;
- &jar;
- &zip;

#ref(https://lh4.googleusercontent.com/-3GsdpxueSG8/Udl1tOfisII/AAAAAAAABvc/SBOIf1ZPPUk/s800/FlatteningPathIterator.png)

** サンプルコード [#zaf3d2bc]
#code(link){{
PathIterator i = new FlatteningPathIterator(shape.getPathIterator(null), 1.0);
float[] coords = new float[6];
while(!i.isDone()) {
  i.currentSegment(coords);
  g2.fillRect((int)(coords[0]-.5), (int)(coords[1]-.5), 2, 2);
  i.next();
}
}}

** 解説 [#he1dd0a1]
- `Ellipse2D`
-- `new Ellipse2D.Double`で作成した`Shape`を描画
- `Polygon` x 2
-- 上記の楕円を`360/60`度ごとに曲線上の座標点を取得し、`Polygon`に変換して直線で描画

#code{{
private static Polygon convertEllipse2Polygon(Ellipse2D e) {
  Rectangle b = e.getBounds();
  int r1 = b.width/2, r2 = b.height/2;
  int x0 = b.x + r1,  y0 = b.y + r2;
  int v  = 60;
  double a = 0.0, d = 2*Math.PI/v;
  Polygon polygon = new Polygon();
  for(int i=0; i<v; i++) {
    polygon.addPoint((int)(r1*Math.cos(a)+x0), (int)(r2*Math.sin(a)+y0));
    a+=d;
  }
  return polygon;
}
}}

- `FlatteningPathIterator`
-- 上記の楕円から取得した`PathIterator`を`FlatteningPathIterator`で平坦化して曲線上の座標点を取得し、`Polygon`に変換して直線で描画
-- 参考: [http://java-sl.com/tip_flatteningpathiterator_moving_shape.html FlatteningPathIterator and moving object along Shape path.]
--- via: [http://stackoverflow.com/questions/17272912/converting-an-ellipse2d-to-polygon java - Converting an Ellipse2D to Polygon - Stack Overflow]
-- `FlatteningPathIterator`を使う方法なら、どんな`Shape`でも平坦化した座標点を簡単に取得できる

** 参考リンク [#h538446e]
- [http://docs.oracle.com/javase/jp/7/api/java/awt/geom/FlatteningPathIterator.html FlatteningPathIterator (Java Platform SE 7 )]
- [http://java-sl.com/tip_flatteningpathiterator_moving_shape.html FlatteningPathIterator and moving object along Shape path.]
-- このサイトの例のように、`Shape`のパスに添ってアニメーションさせる場合などに便利です。

** コメント [#j840d88e]
#comment