Created
January 11, 2015 16:33
-
-
Save santiaago/a749e510cd95d50314db to your computer and use it in GitHub Desktop.
Building a chessboard image in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"image" | |
"image/color" | |
"image/jpeg" | |
"log" | |
"os" | |
) | |
func main() { | |
m := image.NewRGBA(image.Rect(0, 0, 240, 240)) | |
white := color.RGBA{uint8(255), uint8(255), 255, 255} | |
black := color.RGBA{uint8(0), uint8(0), 0, 255} | |
drawGrid(m, black, white) | |
if img, err := os.Create("chessboard.jpg"); err != nil { | |
log.Println("unable to create img.jpg: %v", err) | |
} else { | |
jpeg.Encode(img, m, nil) | |
defer img.Close() | |
} | |
} | |
func drawGrid(m *image.RGBA, color1, color2 color.RGBA) { | |
size := m.Bounds().Size() | |
quad := size.X / 6 | |
for x := 0; x < size.X; x++ { | |
val := (x / quad) % 2 | |
for y := 0; y < size.Y; y++ { | |
val2 := (y / quad) % 2 | |
if (val+val2)%2 == 0 { | |
m.Set(x, y, color1) | |
} else { | |
m.Set(x, y, color2) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you could remove the first and second time you use modulo and just use the third.
also, if your colors are stored in an array, you could rewrite the last
if
and just call