Saturday, August 04, 2012

groovyで三角模様を描画する - その2

groovyで三角模様を描画するには、以下のコードを実行します。
import java.io.*
import java.awt.*
import java.awt.geom.*
import java.awt.image.*
import javax.imageio.*

// 三角模様を描画する - その2
def img = new BufferedImage(
    200, 200, BufferedImage.TYPE_INT_RGB
)
def gr = img.createGraphics()
gr.setRenderingHint(
  RenderingHints.KEY_ANTIALIASING,
  RenderingHints.VALUE_ANTIALIAS_ON
)

def size = 15
def color1 = new Color(0xCCDDFF)
def color2 = new Color(0xFFFFFF)
def xpoints = new int[3]
def ypoints = new int[3]

gr.setColor(color2)
gr.fillRect(0, 0, img.getWidth(), img.getHeight())
gr.setColor(color1)
int rc = 1;
for(int ly=0;ly<img.getHeight()+size;ly+=size){
  for(int lx=0;lx<img.getWidth()+size;lx+=size){
    xpoints[0] = (rc%2==0)?(int)(lx+size/2):lx;
    ypoints[0] = ly
    xpoints[1] = (rc%2==0)?lx+size:(int)(lx+size/2);
    ypoints[1] = ly+size
    xpoints[2] = (rc%2==0)?lx:(int)(lx-size/2);
    ypoints[2] = ly+size
    gr.fillPolygon(xpoints, ypoints, 3)
  }
  rc++;
}
gr.dispose()
ImageIO.write(img, "png", new File("drawtriangles2.png"))


出力画像


動作環境
groovy 1.8.6, JDK7 update4

No comments: