zntg/ui/icon.go
Sander Schobers 432281f08d Added Slider.
Refactored Icon related methods & added alpha support for icon/image generation.
2019-07-08 19:17:11 +02:00

86 lines
1.8 KiB
Go

package ui
import (
"image"
"image/color"
"opslag.de/schobers/geom"
)
type ImagePixelTestFn func(geom.PointF32) bool
type ImageAlphaPixelTestFn func(geom.PointF32) uint8
func createImage(ctx Context, image image.Image) Image {
im, err := ctx.Renderer().CreateImage(image)
if err != nil {
return nil
}
return im
}
func CreateIcon(ctx Context, test ImagePixelTestFn) Image {
icon := DrawIcon(test)
return createImage(ctx, icon)
}
func CreateImage(ctx Context, size geom.Point, test ImagePixelTestFn) Image {
image := DrawImage(size, test)
return createImage(ctx, image)
}
func CreateImageAlpha(ctx Context, size geom.Point, test ImageAlphaPixelTestFn) Image {
image := DrawImageAlpha(size, test)
return createImage(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
}
func GetOrCreateIcon(ctx Context, name string, testFactory func() ImagePixelTestFn) Image {
im := ctx.Images().Image(name)
if im != nil {
return im
}
test := testFactory()
im = CreateIcon(ctx, test)
if im == nil {
return nil
}
ctx.Images().AddImage(name, im)
return im
}
func IconSize() geom.Point {
return geom.Pt(448, 512)
}