zntg/ui/icon.go

86 lines
1.9 KiB
Go
Raw Normal View History

package ui
import (
"image"
"image/color"
"opslag.de/schobers/geom"
)
type ImagePixelTestFn func(geom.PointF32) bool
type ImageAlphaPixelTestFn func(geom.PointF32) uint8
2020-05-12 21:03:43 +00:00
func createTexture(ctx Context, image image.Image) Texture {
texture, err := ctx.Renderer().CreateTexture(image)
if err != nil {
return nil
}
2020-05-12 21:03:43 +00:00
return texture
}
2020-05-12 21:03:43 +00:00
func CreateIcon(ctx Context, test ImagePixelTestFn) Texture {
icon := DrawIcon(test)
2020-05-12 21:03:43 +00:00
return createTexture(ctx, icon)
}
2020-05-12 21:03:43 +00:00
func CreateTexture(ctx Context, size geom.Point, test ImagePixelTestFn) Texture {
image := DrawImage(size, test)
2020-05-12 21:03:43 +00:00
return createTexture(ctx, image)
}
2020-05-12 21:03:43 +00:00
func CreateTextureAlpha(ctx Context, size geom.Point, test ImageAlphaPixelTestFn) Texture {
image := DrawImageAlpha(size, test)
2020-05-12 21:03:43 +00:00
return createTexture(ctx, image)
}
func DrawIcon(test ImagePixelTestFn) image.Image {
size := IconSize()
return DrawImage(size, test)
}
func DrawImage(size geom.Point, test ImagePixelTestFn) image.Image {
r := image.Rect(0, 0, size.X, size.Y)
icon := image.NewRGBA(r)
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
pt := geom.PtF32(float32(x), float32(y))
if test(pt) {
icon.Set(x, y, color.White)
}
}
}
return icon
}
func DrawImageAlpha(size geom.Point, test ImageAlphaPixelTestFn) image.Image {
r := image.Rect(0, 0, size.X, size.Y)
icon := image.NewAlpha(r)
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
pt := geom.PtF32(float32(x), float32(y))
if a := test(pt); a > 0 {
icon.Set(x, y, color.Alpha{A: a})
}
}
}
return icon
}
2020-05-12 21:03:43 +00:00
func GetOrCreateIcon(ctx Context, name string, testFactory func() ImagePixelTestFn) Texture {
texture := ctx.Textures().Texture(name)
if texture != nil {
return texture
}
test := testFactory()
2020-05-12 21:03:43 +00:00
texture = CreateIcon(ctx, test)
if texture == nil {
return nil
}
2020-05-12 21:03:43 +00:00
ctx.Textures().AddTexture(name, texture)
return texture
}
func IconSize() geom.Point {
return geom.Pt(448, 512)
}