Tuesday, July 31, 2012

groovyでピラミッド模様を描画する

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

// ピラミッド模様を描画する
def img = new BufferedImage(
  200, 200, BufferedImage.TYPE_INT_ARGB
)
def gr = img.createGraphics()

def size = 20

def base = new Color(0x5577bb)
def hsb = new float[3]
Color.RGBtoHSB(base.getRed(), base.getGreen(), base.getBlue(), hsb)
def brighter = new Color(Color.HSBtoRGB(hsb[0], hsb[1], (float)hsb[2]*1.2>1?1:hsb[2]*1.1))
def brighter2 = new Color(Color.HSBtoRGB(hsb[0], hsb[1], (float)hsb[2]*1.2>1?1:hsb[2]*1.2))
def darker = new Color(Color.HSBtoRGB(hsb[0], hsb[1], (float)hsb[2]*0.9))
def darker2 = new Color(Color.HSBtoRGB(hsb[0], hsb[1], (float)hsb[2]*0.8))

def xpoints = new int[3]
def ypoints = new int[3]
for(int ly=0;ly<img.getHeight()+size;ly+=size){
  for(int lx=0;lx<img.getWidth()+size;lx+=size){
    gr.setColor(brighter2)
    xpoints[0] = lx
    ypoints[0] = ly
    xpoints[1] = lx+size
    ypoints[1] = ly
    xpoints[2] = (int)lx+size/2
    ypoints[2] = (int)ly+size/2
    gr.fillPolygon(xpoints, ypoints, 3)

    gr.setColor(brighter)
    xpoints[0] = lx
    ypoints[0] = ly
    xpoints[1] = lx
    ypoints[1] = ly+size
    xpoints[2] = (int)lx+size/2
    ypoints[2] = (int)ly+size/2
    gr.fillPolygon(xpoints, ypoints, 3)

    gr.setColor(darker)
    xpoints[0] = lx+size
    ypoints[0] = ly
    xpoints[1] = lx+size
    ypoints[1] = ly+size
    xpoints[2] = (int)lx+size/2
    ypoints[2] = (int)ly+size/2
    gr.fillPolygon(xpoints, ypoints, 3)

    gr.setColor(darker2)
    xpoints[0] = lx
    ypoints[0] = ly+size
    xpoints[1] = lx+size
    ypoints[1] = ly+size
    xpoints[2] = (int)lx+size/2
    ypoints[2] = (int)ly+size/2
    gr.fillPolygon(xpoints, ypoints, 3)
  }
}
gr.dispose()

ImageIO.write(img, "png", new File("drawpyramid.png"))


出力画像


動作環境
groovy 1.8.6, JDK7 update4

No comments: