image.go raw
1 // SPDX-License-Identifier: Unlicense OR MIT
2
3 package gel
4
5 import (
6 "image"
7
8 "github.com/p9c/gio/layout"
9 "github.com/p9c/gio/op"
10 "github.com/p9c/gio/op/clip"
11 "github.com/p9c/gio/op/paint"
12 "github.com/p9c/gio/unit"
13 )
14
15 // Image is a widget that displays an image.
16 type Image struct {
17 // src is the image to display.
18 src paint.ImageOp
19 // scale is the ratio of image pixels to dps. If scale is zero Image falls back to a scale that match a standard 72
20 // DPI.
21 scale float32
22 }
23
24 func (th *Theme) Image() *Image {
25 return &Image{}
26 }
27
28 func (i *Image) Src(img paint.ImageOp) *Image {
29 i.src = img
30 return i
31 }
32
33 func (i *Image) Scale(scale float32) *Image {
34 i.scale = scale
35 return i
36 }
37
38 func (i Image) Fn(gtx layout.Context) layout.Dimensions {
39 scale := i.scale
40 if scale == 0 {
41 scale = 160.0 / 72.0
42 }
43 size := i.src.Size()
44 wf, hf := float32(size.X), float32(size.Y)
45 w, h := gtx.Px(unit.Dp(wf*scale)), gtx.Px(unit.Dp(hf*scale))
46 cs := gtx.Constraints
47 d := cs.Constrain(image.Pt(w, h))
48 stack := op.Save(gtx.Ops)
49 clip.Rect(image.Rectangle{Max: d}).Add(gtx.Ops)
50 i.src.Add(gtx.Ops)
51 paint.PaintOp{}.Add(gtx.Ops)
52 stack.Load()
53 return layout.Dimensions{Size: size}
54 }
55