forked from jkvatne/gio-v
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.go
83 lines (70 loc) · 1.79 KB
/
image.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// SPDX-License-Identifier: Unlicense OR MIT
package wid
import (
"fmt"
"image"
_ "image/jpeg"
"os"
"gioui.org/f32"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/op/clip"
"gioui.org/op/paint"
)
// )
// ImageDef is a widget that displays an image.
type ImageDef struct {
// Src is the image to display.
Src paint.ImageOp
// Fit specifies how to scale the image to the constraints.
// By default, it does not do any scaling.
Fit Fit
// Position specifies where to position the image within
// the constraints.
Position layout.Direction
// Scale is the ratio of image pixels to
// dps. If Scale is zero Image falls back to
// a scale that match a standard 72 DPI.
Scale float32
}
func ImageFromJpgFile(filename string, fit Fit) func(gtx C) D {
f, err := os.Open(filename)
defer func() {
err := f.Close()
if err != nil {
panic("Jpg file close failed")
}
}()
if err != nil {
panic(fmt.Sprintf("Image '%s' not found", filename))
}
pict, _, err := image.Decode(f)
if err != nil {
panic(fmt.Sprintf("Image '%s' has unknown format", filename))
}
return Image(pict, fit)
}
func Image(img image.Image, fit Fit) func(gtx C) D {
src := paint.NewImageOp(img)
im := ImageDef{}
im.Fit = fit
im.Src = src
return func(gtx C) D {
return im.Layout(gtx)
}
}
func (im ImageDef) Layout(gtx C) D {
scale := im.Scale
if scale == 0 {
scale = gtx.Metric.PxPerDp
}
w := int(float32(im.Src.Size().X) * scale)
h := int(float32(im.Src.Size().Y) * scale)
dims, trans := im.Fit.scale(gtx.Constraints, im.Position, layout.Dimensions{Size: image.Pt(w, h)})
defer clip.Rect{Max: dims.Size}.Push(gtx.Ops).Pop()
trans = trans.Mul(f32.Affine2D{}.Scale(f32.Point{}, f32.Pt(scale, scale)))
defer op.Affine(trans).Push(gtx.Ops).Pop()
im.Src.Add(gtx.Ops)
paint.PaintOp{}.Add(gtx.Ops)
return dims
}