2019-03-05 20:52:18 +00:00
|
|
|
package ui
|
|
|
|
|
2019-04-10 20:41:28 +00:00
|
|
|
import "github.com/nfnt/resize"
|
2019-03-05 20:52:18 +00:00
|
|
|
|
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-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
2019-04-10 20:41:28 +00:00
|
|
|
type Images struct {
|
|
|
|
render Renderer
|
|
|
|
ims map[string]Image
|
|
|
|
scaled map[Image]ScaledImages
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
2019-04-10 20:41:28 +00:00
|
|
|
func NewImages(render Renderer) *Images {
|
|
|
|
return &Images{render, map[string]Image{}, map[Image]ScaledImages{}}
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (i *Images) AddImage(name string, im Image) {
|
2019-04-10 20:41:28 +00:00
|
|
|
curr := i.ims[name]
|
2019-03-05 20:52:18 +00:00
|
|
|
if curr != nil {
|
|
|
|
curr.Destroy()
|
|
|
|
}
|
2019-04-10 20:41:28 +00:00
|
|
|
i.ims[name] = im
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (i *Images) Destroy() {
|
2019-04-10 20:41:28 +00:00
|
|
|
for _, im := range i.ims {
|
2019-03-05 20:52:18 +00:00
|
|
|
im.Destroy()
|
|
|
|
}
|
2019-04-10 20:41:28 +00:00
|
|
|
i.ims = nil
|
|
|
|
for _, ims := range i.scaled {
|
|
|
|
ims.Destroy()
|
|
|
|
}
|
|
|
|
i.scaled = nil
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
2019-04-10 20:41:28 +00:00
|
|
|
func (i *Images) Image(name string) Image {
|
|
|
|
im, ok := i.ims[name]
|
2019-03-05 20:52:18 +00:00
|
|
|
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 {
|
2019-03-05 20:52:18 +00:00
|
|
|
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 {
|
2019-03-05 20:52:18 +00:00
|
|
|
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()
|
|
|
|
}
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|