Saturday, August 04, 2012

groovyでひし形模様を描画する

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

// ひし形模様を描画する 
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 = 20
def color1 = new Color(0x7799dd)
def color2 = new Color(0xFFFFFF)
def xpoints = new int[4]
def ypoints = new int[4]

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)?(int)(lx+size*3/4):(int)(lx+size*1/4);
    ypoints[1] = (int)(ly+size/2)
    xpoints[2] = (rc%2==0)?(int)(lx+size/2):lx;
    ypoints[2] = ly+size
    xpoints[3] = (rc%2==0)?(int)(lx+size*1/4):(int)(lx-size*1/4);
    ypoints[3] = (int)(ly+size/2)
    gr.fillPolygon(xpoints, ypoints, 4)
  }
  rc++;
}
gr.dispose()
ImageIO.write(img, "png", new File("drawrhombus.png"))


出力画像


動作環境
groovy 1.8.6, JDK7 update4

No comments: