zntg/ui/images.go

92 lines
1.5 KiB
Go
Raw Normal View History

package ui
2019-04-10 20:41:28 +00:00
import "github.com/nfnt/resize"
2019-04-10 20:41:28 +00:00
func ScaleImage(render Renderer, im Image, scale float32) Image {
w := uint(im.Width() * scale)
if w == 0 {
return nil
}
scaled := resize.Resize(w, 0, im.Image(), resize.Bilinear)
res, err := render.CreateImage(scaled)
if err != nil {
return nil
}
return res
}
2019-04-10 20:41:28 +00:00
type Images struct {
render Renderer
ims map[string]Image
scaled map[Image]ScaledImages
}
2019-04-10 20:41:28 +00:00
func NewImages(render Renderer) *Images {
return &Images{render, map[string]Image{}, map[Image]ScaledImages{}}
}
func (i *Images) AddImage(name string, im Image) {
2019-04-10 20:41:28 +00:00
curr := i.ims[name]
if curr != nil {
curr.Destroy()
}
2019-04-10 20:41:28 +00:00
i.ims[name] = im
}
func (i *Images) Destroy() {
2019-04-10 20:41:28 +00:00
for _, im := range i.ims {
im.Destroy()
}
2019-04-10 20:41:28 +00:00
i.ims = nil
for _, ims := range i.scaled {
ims.Destroy()
}
i.scaled = nil
}
2019-04-10 20:41:28 +00:00
func (i *Images) Image(name string) Image {
im, ok := i.ims[name]
if ok {
return im
}
2019-04-10 20:41:28 +00:00
return nil
}
func (i *Images) Scaled(im Image, scale float32) Image {
if scale <= 0 {
return nil
}
2019-04-10 20:41:28 +00:00
if scale == 1 {
return im
}
ims := i.scaled[im]
if ims == nil {
ims = make(ScaledImages)
} else {
scaled := ims[scale]
if scaled != nil {
return scaled
}
}
scaled := ScaleImage(i.render, im, scale)
ims[scale] = scaled
i.scaled[im] = ims
return scaled
}
func (i *Images) ScaledByName(name string, scale float32) Image {
im := i.Image(name)
if im == nil {
return nil
}
2019-04-10 20:41:28 +00:00
return i.Scaled(im, scale)
}
type ScaledImages map[float32]Image
func (i ScaledImages) Destroy() {
for _, im := range i {
im.Destroy()
}
}