Debian Codegraph @

vendor/github.com/xyproto/palgen/render.go

raw
1 package palgen
2
3 import (
4 "image"
5 "image/color"
6 )
7
8 // Render a given palette as an image, with blocks of 16x16 pixels and 32 colors per row of blocks.
9 func Render(pal color.Palette) image.Image {
10 return RenderWithConfig(pal, 16, 32)
11 }
12
13 // RenderWithConfig can render a given palette as an image that shows each color as a square, lined up in rows.
14 // blockSize is the size of the color block per color, in pixels (16 is default)
15 // colorsPerRow is the number of color blocks per row (32 is default)
16 func RenderWithConfig(pal color.Palette, blockSize, colorsPerRow int) image.Image {
17
18 // Remove the alpha
19 for i, c := range pal {
20 rgba := color.RGBAModel.Convert(c).(color.RGBA)
21 rgba.A = 255
22 pal[i] = rgba
23 }
24
25 // The first color is now the darkest one
26 darkIndex := uint8(0)
27
28 // Let each row have colorsPerRow blocks
29 w := colorsPerRow
30 h := len(pal) / w
31 leftover := len(pal) % w
32 if leftover > 0 {
33 h++
34 }
35
36 // "pixel" width and height
37 pw := blockSize
38 ph := blockSize
39
40 // TODO: Clean up everything that has to do with borderSize and support
41 // custom border sizes.
42
43 // size of border, ish
44 borderSize := 2
45
46 upLeft := image.Point{0, 0}
47 lowRight := image.Point{w*pw + (borderSize-1)*2, h*ph + (borderSize-1)*2}
48
49 // Create a new image, where a square is painted per color in the palette
50 palImage := image.NewPaletted(image.Rectangle{upLeft, lowRight}, pal)
51
52 for y := upLeft.Y; y < lowRight.Y; y++ {
53 for x := upLeft.X; x < lowRight.X; x++ {
54 if x < (borderSize-1) || y < (borderSize-1) || x >= (lowRight.X-(borderSize-1)) || y >= (lowRight.Y-(borderSize-1)) {
55 palImage.SetColorIndex(x, y, darkIndex)
56 }
57 }
58 }
59
60 // Set color for each pixel.
61 colorIndex := uint8(0)
62 OUT:
63 // For each palette color block
64 for y := 0; y < h; y++ {
65 for x := range w {
66 // For each pixel in the block of size pw x ph
67 for by := range ph {
68 for bx := range pw {
69 if bx <= borderSize-2 || by <= borderSize-2 || bx >= pw-(borderSize-1) || by >= ph-(borderSize-1) {
70 palImage.SetColorIndex((x*pw)+bx+(borderSize-1), (y*ph)+by+(borderSize-1), darkIndex)
71 } else {
72 palImage.SetColorIndex((x*pw)+bx+(borderSize-1), (y*ph)+by+(borderSize-1), colorIndex)
73 }
74 }
75 }
76 colorIndex++
77 if int(colorIndex) >= len(pal) {
78 break OUT
79 }
80 }
81 }
82
83 return palImage
84 }