Skip to content

Commit 421aa5c

Browse files
Add files via upload
1 parent 76ac687 commit 421aa5c

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

exp/util/drawText.go

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package util
2+
3+
import (
4+
"image"
5+
"image/color"
6+
"image/draw"
7+
"strings"
8+
9+
"golang.org/x/image/font"
10+
"golang.org/x/image/font/basicfont"
11+
"golang.org/x/image/math/fixed"
12+
13+
"golang.org/x/mobile/event/size"
14+
"golang.org/x/mobile/exp/gl/glutil"
15+
"golang.org/x/mobile/geom"
16+
)
17+
18+
func drawText(img *image.RGBA, x, y int, s string) {
19+
col := color.RGBA{0, 0, 0, 255}
20+
point := fixed.Point26_6{fixed.I(x), fixed.I(y)}
21+
22+
d := &font.Drawer{
23+
Dst: img,
24+
Src: image.NewUniform(col),
25+
Face: basicfont.Face7x13,
26+
Dot: point,
27+
}
28+
d.DrawString(s)
29+
}
30+
31+
// Text draws text to screen
32+
type Text struct {
33+
sz size.Event
34+
images *glutil.Images
35+
m *glutil.Image
36+
// TODO: store *gl.Context
37+
}
38+
39+
// NewText creates a Text tied to the current GL context.
40+
func NewText(images *glutil.Images) *Text {
41+
return &Text{
42+
images: images,
43+
}
44+
}
45+
46+
// Draw draws text at the x, y coordinates at the scaleX, scaleY specified by user
47+
// Draw accepts strings with newline characters
48+
func (t *Text) Draw(sz size.Event, x, y int, scaleX, scaleY geom.Pt, s string) {
49+
if sz.WidthPx == 0 && sz.HeightPx == 0 {
50+
return
51+
} else if t.m == nil {
52+
t.sz = sz
53+
if t.m != nil {
54+
t.m.Release()
55+
}
56+
t.m = t.images.NewImage(sz.WidthPx, sz.HeightPx)
57+
}
58+
59+
// split string by newline
60+
lines := strings.Split(s, "\n")
61+
62+
// draw each string on a seperate line
63+
for i, v := range lines {
64+
drawText(t.m.RGBA, int(geom.Pt(x)/scaleX), int(geom.Pt(y)/scaleY)+i*10, v)
65+
}
66+
67+
// copy img data to GL device
68+
t.m.Upload()
69+
70+
t.m.Draw(
71+
sz,
72+
geom.Point{0, 0}, // topLeft
73+
geom.Point{sz.WidthPt * scaleX, 0}, // topRight
74+
geom.Point{0, sz.HeightPt * scaleY}, // bottomLeft
75+
t.m.RGBA.Bounds(),
76+
)
77+
}
78+
79+
func (t *Text) Clear() {
80+
if t.m != nil {
81+
draw.Draw(t.m.RGBA, t.m.RGBA.Bounds(), image.Transparent, image.Point{}, draw.Src)
82+
}
83+
}
84+
85+
func (t *Text) Release() {
86+
if t.m != nil {
87+
t.m.Release()
88+
t.m = nil
89+
t.images = nil
90+
}
91+
}

0 commit comments

Comments
 (0)