Files
gio-patched/widget/icon.go
T
Elias Naur 3af01a3f43 layout: change Widget to take explicit Context and return explicit Dimensions
Change the definition of Widget from the implicit

        type Widget func()

to the explicit functional

        type Widget func(gtx layout.Context) layout.Dimensions

The advantages are numerous:

- Clearer connection between the incoming context and the output dimensions.
- Returning the Dimensions are impossible to omit.
- Contexts passed by value, so its fields can be exported
and freely mutated by the program.

The only disadvantage is the longer function literals and the many "returns".
What tipped the scales in favour of the explicit Widget variant is that type
aliases can dramatically shorten the literals:

	type (
		C = layout.Context
		D = layout.Dimensions
	)

	widget := func(gtx C) D {
		...
	}

Note that the aliases are not part of the Gio API and it is up to each user
whether they want to use them.

Finally the Go proposal for lightweight function literals,
https://github.com/golang/go/issues/21498, may remove the disadvantage
completely in future.

Context becomes a plain struct with only public fields, and its Reset is
replaced by a NewContext convenience constructor.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-05-23 22:28:49 +02:00

66 lines
1.4 KiB
Go

// SPDX-License-Identifier: Unlicense OR MIT
package widget
import (
"image"
"image/color"
"image/draw"
"gioui.org/f32"
"gioui.org/layout"
"gioui.org/op/paint"
"gioui.org/unit"
"golang.org/x/exp/shiny/iconvg"
)
type Icon struct {
Color color.RGBA
src []byte
// Cached values.
op paint.ImageOp
imgSize int
imgColor color.RGBA
}
// NewIcon returns a new Icon from IconVG data.
func NewIcon(data []byte) (*Icon, error) {
_, err := iconvg.DecodeMetadata(data)
if err != nil {
return nil, err
}
return &Icon{src: data, Color: color.RGBA{A: 0xff}}, nil
}
func (ic *Icon) Layout(gtx layout.Context, sz unit.Value) layout.Dimensions {
ico := ic.image(gtx.Px(sz))
ico.Add(gtx.Ops)
paint.PaintOp{
Rect: f32.Rectangle{
Max: layout.FPt(ico.Size()),
},
}.Add(gtx.Ops)
return layout.Dimensions{
Size: ico.Size(),
}
}
func (ic *Icon) image(sz int) paint.ImageOp {
if sz == ic.imgSize && ic.Color == ic.imgColor {
return ic.op
}
m, _ := iconvg.DecodeMetadata(ic.src)
dx, dy := m.ViewBox.AspectRatio()
img := image.NewRGBA(image.Rectangle{Max: image.Point{X: sz, Y: int(float32(sz) * dy / dx)}})
var ico iconvg.Rasterizer
ico.SetDstImage(img, img.Bounds(), draw.Src)
m.Palette[0] = ic.Color
iconvg.Decode(&ico, ic.src, &iconvg.DecodeOptions{
Palette: &m.Palette,
})
ic.op = paint.NewImageOp(img)
ic.imgSize = sz
ic.imgColor = ic.Color
return ic.op
}