edbit/application/pallette.go

80 lines
1.5 KiB
Go

package application
import (
"image"
"image/color"
"math"
"github.com/hajimehoshi/ebiten/v2"
)
type colorPalette struct {
x, y int
w, h int
columns int
img *ebiten.Image
colors []color.RGBA
colorRects []image.Rectangle
op *ebiten.DrawImageOptions
}
func NewPalette() *colorPalette {
return &colorPalette{
op: &ebiten.DrawImageOptions{},
}
}
func (p *colorPalette) setRect(x, y, w, h int) {
if p.x == x && p.y == y && p.w == w && p.h == h {
return
}
redraw := p.w != w || p.h != h
p.x, p.y, p.w, p.h = x, y, w, h
if redraw {
p.drawBuffer()
}
}
func (p *colorPalette) drawBuffer() {
p.img = ebiten.NewImage(p.w, p.h)
p.img.Fill(color.Black)
p.colorRects = make([]image.Rectangle, len(p.colors))
rows := int(math.Ceil(float64(len(p.colors)) / float64(p.columns)))
swatchWidth := p.w / p.columns
swatchHeight := p.h / rows
for i, colorSwatch := range p.colors {
row := i / p.columns
x, y := (i%p.columns)*swatchWidth, row*swatchHeight
p.colorRects[i] = image.Rect(x, y, x+swatchWidth, y+swatchHeight)
p.img.SubImage(p.colorRects[i]).(*ebiten.Image).Fill(colorSwatch)
}
}
func (p *colorPalette) colorSwatchAt(x, y int) (color.RGBA, bool) {
for i, colorRect := range p.colorRects {
point := image.Point{x, y}
if point.In(colorRect) {
return p.colors[i], true
}
}
return color.RGBA{}, false
}
func (p *colorPalette) Draw(screen *ebiten.Image) {
p.op.GeoM.Reset()
p.op.GeoM.Translate(float64(p.x), float64(p.y))
screen.DrawImage(p.img, p.op)
}