Source file
doc/progs/image_draw.go
1
2
3
4
5
6
7 package main
8
9 import (
10 "image"
11 "image/color"
12 "image/draw"
13 )
14
15 func main() {
16 Color()
17 Rect()
18 RectAndScroll()
19 ConvAndCircle()
20 Glyph()
21 }
22
23 func Color() {
24 c := color.RGBA{255, 0, 255, 255}
25 r := image.Rect(0, 0, 640, 480)
26 dst := image.NewRGBA(r)
27
28
29
30 draw.Draw(dst, r, &image.Uniform{c}, image.ZP, draw.Src)
31
32
33
34 m := image.NewRGBA(image.Rect(0, 0, 640, 480))
35 blue := color.RGBA{0, 0, 255, 255}
36 draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)
37
38
39
40 draw.Draw(m, m.Bounds(), image.Transparent, image.ZP, draw.Src)
41
42 }
43
44 func Rect() {
45 dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
46 sr := image.Rect(0, 0, 200, 200)
47 src := image.Black
48 dp := image.Point{100, 100}
49
50
51 r := image.Rectangle{dp, dp.Add(sr.Size())}
52 draw.Draw(dst, r, src, sr.Min, draw.Src)
53
54 }
55
56 func RectAndScroll() {
57 dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
58 sr := image.Rect(0, 0, 200, 200)
59 src := image.Black
60 dp := image.Point{100, 100}
61
62
63 r := sr.Sub(sr.Min).Add(dp)
64 draw.Draw(dst, r, src, sr.Min, draw.Src)
65
66
67 m := dst
68
69
70 b := m.Bounds()
71 p := image.Pt(0, 20)
72
73
74 draw.Draw(m, b, m, b.Min.Add(p), draw.Src)
75 dirtyRect := b.Intersect(image.Rect(b.Min.X, b.Max.Y-20, b.Max.X, b.Max.Y))
76
77
78 _ = dirtyRect
79 }
80
81 func ConvAndCircle() {
82 src := image.NewRGBA(image.Rect(0, 0, 640, 480))
83 dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
84
85
86 b := src.Bounds()
87 m := image.NewRGBA(b)
88 draw.Draw(m, b, src, b.Min, draw.Src)
89
90
91 p := image.Point{100, 100}
92 r := 50
93
94
95 draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over)
96
97 }
98
99 func theGlyphImageForAFont() image.Image {
100 return image.NewRGBA(image.Rect(0, 0, 640, 480))
101 }
102
103 func theBoundsFor(index int) image.Rectangle {
104 return image.Rect(0, 0, 32, 32)
105 }
106
107 func Glyph() {
108 p := image.Point{100, 100}
109 dst := image.NewRGBA(image.Rect(0, 0, 640, 480))
110 glyphIndex := 42
111
112
113 src := &image.Uniform{color.RGBA{0, 0, 255, 255}}
114 mask := theGlyphImageForAFont()
115 mr := theBoundsFor(glyphIndex)
116 draw.DrawMask(dst, mr.Sub(mr.Min).Add(p), src, image.ZP, mask, mr.Min, draw.Over)
117
118 }
119
120
121 type circle struct {
122 p image.Point
123 r int
124 }
125
126 func (c *circle) ColorModel() color.Model {
127 return color.AlphaModel
128 }
129
130 func (c *circle) Bounds() image.Rectangle {
131 return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r)
132 }
133
134 func (c *circle) At(x, y int) color.Color {
135 xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r)
136 if xx*xx+yy*yy < rr*rr {
137 return color.Alpha{255}
138 }
139 return color.Alpha{0}
140 }
141
142
143
View as plain text