-
Notifications
You must be signed in to change notification settings - Fork 204
/
vgimg.go
392 lines (341 loc) · 9.21 KB
/
vgimg.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package vgimg implements the vg.Canvas interface using
// github.com/fogleman/gg as a backend to output raster images.
package vgimg // import "gonum.org/v1/plot/vg/vgimg"
import (
"bufio"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"io"
"github.com/fogleman/gg"
"golang.org/x/image/tiff"
"gonum.org/v1/plot/vg"
)
// Canvas implements the vg.Canvas interface,
// drawing to an image.Image using draw2d.
type Canvas struct {
ctx *gg.Context
img draw.Image
w, h vg.Length
color []color.Color
// dpi is the number of dots per inch for this canvas.
dpi int
// width is the current line width.
width vg.Length
// backgroundColor is the background color, set by
// UseBackgroundColor.
backgroundColor color.Color
}
const (
// DefaultDPI is the default dot resolution for image
// drawing in dots per inch.
DefaultDPI = 96
// DefaultWidth and DefaultHeight are the default canvas
// dimensions.
DefaultWidth = 4 * vg.Inch
DefaultHeight = 4 * vg.Inch
)
// New returns a new image canvas.
func New(w, h vg.Length) *Canvas {
return NewWith(UseWH(w, h), UseBackgroundColor(color.White))
}
// NewWith returns a new image canvas created according to the specified
// options. The currently accepted options are UseWH,
// UseDPI, UseImage, and UseImageWithContext.
// Each of the options specifies the size of the canvas (UseWH, UseImage),
// the resolution of the canvas (UseDPI), or both (useImageWithContext).
// If size or resolution are not specified, defaults are used.
// It panics if size and resolution are overspecified (i.e., too many options are
// passed).
func NewWith(o ...option) *Canvas {
c := new(Canvas)
c.backgroundColor = color.White
var g uint32
for _, opt := range o {
f := opt(c)
if g&f != 0 {
panic("incompatible options")
}
g |= f
}
if c.dpi == 0 {
c.dpi = DefaultDPI
}
if c.w == 0 { // h should also == 0.
if c.img == nil {
c.w = DefaultWidth
c.h = DefaultHeight
} else {
w := float64(c.img.Bounds().Max.X - c.img.Bounds().Min.X)
h := float64(c.img.Bounds().Max.Y - c.img.Bounds().Min.Y)
c.w = vg.Length(w/float64(c.dpi)) * vg.Inch
c.h = vg.Length(h/float64(c.dpi)) * vg.Inch
}
}
if c.img == nil {
w := c.w / vg.Inch * vg.Length(c.dpi)
h := c.h / vg.Inch * vg.Length(c.dpi)
c.img = draw.Image(image.NewRGBA(image.Rect(0, 0, int(w+0.5), int(h+0.5))))
}
if c.ctx == nil {
c.ctx = gg.NewContextForImage(c.img)
c.ctx.SetLineCapButt()
c.img = c.ctx.Image().(draw.Image)
c.ctx.InvertY()
}
draw.Draw(c.img, c.img.Bounds(), &image.Uniform{c.backgroundColor}, image.ZP, draw.Src)
c.color = []color.Color{color.Black}
vg.Initialize(c)
return c
}
// These constants are used to ensure that the options
// used when initializing a canvas are compatible with
// each other.
const (
setsDPI uint32 = 1 << iota
setsSize
setsBackground
)
type option func(*Canvas) uint32
// UseWH specifies the width and height of the canvas.
// The size is rounded up to the nearest pixel.
func UseWH(w, h vg.Length) option {
return func(c *Canvas) uint32 {
if w <= 0 || h <= 0 {
panic("w and h must both be > 0.")
}
c.w, c.h = w, h
return setsSize
}
}
// UseDPI sets the dots per inch of a canvas. It should only be
// used as an option argument when initializing a new canvas.
func UseDPI(dpi int) option {
if dpi <= 0 {
panic("DPI must be > 0.")
}
return func(c *Canvas) uint32 {
c.dpi = dpi
return setsDPI
}
}
// UseImage specifies an image to create
// the canvas from. The
// minimum point of the given image
// should probably be 0,0.
func UseImage(img draw.Image) option {
return func(c *Canvas) uint32 {
c.img = img
return setsSize | setsBackground
}
}
// UseImageWithContext specifies both an image
// and a graphic context to create the canvas from.
// The minimum point of the given image
// should probably be 0,0.
func UseImageWithContext(img draw.Image, ctx *gg.Context) option {
return func(c *Canvas) uint32 {
c.img = img
c.ctx = ctx
return setsSize | setsBackground
}
}
// UseBackgroundColor specifies the image background color.
// Without UseBackgroundColor, the default color is white.
func UseBackgroundColor(c color.Color) option {
return func(canvas *Canvas) uint32 {
canvas.backgroundColor = c
return setsBackground
}
}
// Image returns the image the canvas is drawing to.
//
// The dimensions of the returned image must not be modified.
func (c *Canvas) Image() draw.Image {
return c.img
}
func (c *Canvas) Size() (w, h vg.Length) {
return c.w, c.h
}
func (c *Canvas) SetLineWidth(w vg.Length) {
c.width = w
c.ctx.SetLineWidth(w.Dots(c.DPI()))
}
func (c *Canvas) SetLineDash(ds []vg.Length, offs vg.Length) {
dashes := make([]float64, len(ds))
for i, d := range ds {
dashes[i] = d.Dots(c.DPI())
}
// FIXME(sbinet): handle offs (the distance into the dash pattern
// to start the dash.)
// this needs to be implemented on the gg side.
// see:
// - https://github.com/fogleman/gg/issues/64
c.ctx.SetDash(dashes...)
}
func (c *Canvas) SetColor(clr color.Color) {
if clr == nil {
clr = color.Black
}
c.ctx.SetColor(clr)
c.color[len(c.color)-1] = clr
}
func (c *Canvas) Rotate(t float64) {
c.ctx.Rotate(t)
}
func (c *Canvas) Translate(pt vg.Point) {
c.ctx.Translate(pt.X.Dots(c.DPI()), pt.Y.Dots(c.DPI()))
}
func (c *Canvas) Scale(x, y float64) {
c.ctx.Scale(x, y)
}
func (c *Canvas) Push() {
c.color = append(c.color, c.color[len(c.color)-1])
c.ctx.Push()
}
func (c *Canvas) Pop() {
c.color = c.color[:len(c.color)-1]
c.ctx.Pop()
}
func (c *Canvas) Stroke(p vg.Path) {
if c.width <= 0 {
return
}
c.outline(p)
c.ctx.Stroke()
}
func (c *Canvas) Fill(p vg.Path) {
c.outline(p)
c.ctx.Fill()
}
func (c *Canvas) outline(p vg.Path) {
for _, comp := range p {
switch comp.Type {
case vg.MoveComp:
c.ctx.MoveTo(comp.Pos.X.Dots(c.DPI()), comp.Pos.Y.Dots(c.DPI()))
case vg.LineComp:
c.ctx.LineTo(comp.Pos.X.Dots(c.DPI()), comp.Pos.Y.Dots(c.DPI()))
case vg.ArcComp:
c.ctx.DrawArc(comp.Pos.X.Dots(c.DPI()), comp.Pos.Y.Dots(c.DPI()),
comp.Radius.Dots(c.DPI()),
comp.Start, comp.Start+comp.Angle,
)
case vg.CurveComp:
switch len(comp.Control) {
case 1:
c.ctx.QuadraticTo(
comp.Control[0].X.Dots(c.DPI()), comp.Control[0].Y.Dots(c.DPI()),
comp.Pos.X.Dots(c.DPI()), comp.Pos.Y.Dots(c.DPI()),
)
case 2:
c.ctx.CubicTo(
comp.Control[0].X.Dots(c.DPI()), comp.Control[0].Y.Dots(c.DPI()),
comp.Control[1].X.Dots(c.DPI()), comp.Control[1].Y.Dots(c.DPI()),
comp.Pos.X.Dots(c.DPI()), comp.Pos.Y.Dots(c.DPI()),
)
default:
panic("vgimg: invalid number of control points")
}
case vg.CloseComp:
c.ctx.ClosePath()
default:
panic(fmt.Sprintf("Unknown path component: %d", comp.Type))
}
}
}
// DPI returns the resolution of the receiver in pixels per inch.
func (c *Canvas) DPI() float64 {
return float64(c.dpi)
}
func (c *Canvas) FillString(font vg.Font, pt vg.Point, str string) {
c.ctx.Push()
defer c.ctx.Pop()
c.ctx.SetFontFace(font.FontFace(c.DPI()))
x := pt.X.Dots(c.DPI())
y := pt.Y.Dots(c.DPI())
h := c.h.Dots(c.DPI())
c.ctx.InvertY()
c.ctx.DrawString(str, x, h-y)
}
// DrawImage implements the vg.Canvas.DrawImage method.
func (c *Canvas) DrawImage(rect vg.Rectangle, img image.Image) {
var (
dpi = c.DPI()
min = rect.Min
xmin = min.X.Dots(dpi)
ymin = min.Y.Dots(dpi)
rsz = rect.Size()
width = rsz.X.Dots(dpi)
height = rsz.Y.Dots(dpi)
dx = float64(img.Bounds().Dx())
dy = float64(img.Bounds().Dy())
)
c.ctx.Push()
c.ctx.Scale(1, -1)
c.ctx.Translate(xmin, -ymin-height)
c.ctx.Scale(width/dx, height/dy)
c.ctx.DrawImage(img, 0, 0)
c.ctx.Pop()
}
// WriterCounter implements the io.Writer interface, and counts
// the total number of bytes written.
type writerCounter struct {
io.Writer
n int64
}
func (w *writerCounter) Write(p []byte) (int, error) {
n, err := w.Writer.Write(p)
w.n += int64(n)
return n, err
}
// A JpegCanvas is an image canvas with a WriteTo method
// that writes a jpeg image.
type JpegCanvas struct {
*Canvas
}
// WriteTo implements the io.WriterTo interface, writing a jpeg image.
func (c JpegCanvas) WriteTo(w io.Writer) (int64, error) {
wc := writerCounter{Writer: w}
b := bufio.NewWriter(&wc)
if err := jpeg.Encode(b, c.img, nil); err != nil {
return wc.n, err
}
err := b.Flush()
return wc.n, err
}
// A PngCanvas is an image canvas with a WriteTo method that
// writes a png image.
type PngCanvas struct {
*Canvas
}
// WriteTo implements the io.WriterTo interface, writing a png image.
func (c PngCanvas) WriteTo(w io.Writer) (int64, error) {
wc := writerCounter{Writer: w}
b := bufio.NewWriter(&wc)
if err := png.Encode(b, c.img); err != nil {
return wc.n, err
}
err := b.Flush()
return wc.n, err
}
// A TiffCanvas is an image canvas with a WriteTo method that
// writes a tiff image.
type TiffCanvas struct {
*Canvas
}
// WriteTo implements the io.WriterTo interface, writing a tiff image.
func (c TiffCanvas) WriteTo(w io.Writer) (int64, error) {
wc := writerCounter{Writer: w}
b := bufio.NewWriter(&wc)
if err := tiff.Encode(b, c.img, nil); err != nil {
return wc.n, err
}
err := b.Flush()
return wc.n, err
}