From d1da415ba698899aafae1d08b087df5e837297c2 Mon Sep 17 00:00:00 2001 From: Michael Fogleman Date: Fri, 19 Feb 2016 13:49:03 -0500 Subject: [PATCH] DrawImage, LoadPNG --- context.go | 8 +++++++- examples/tiling.go | 21 +++++++++++++++++++++ util.go | 11 ++++++++++- 3 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 examples/tiling.go diff --git a/context.go b/context.go index 3c5f2d9..cffe216 100644 --- a/context.go +++ b/context.go @@ -84,7 +84,7 @@ func (dc *Context) Height() int { } func (dc *Context) WritePNG(path string) error { - return writePNG(path, dc.im) + return SavePNG(path, dc.im) } func (dc *Context) SetLineWidth(lineWidth float64) { @@ -303,6 +303,12 @@ func (dc *Context) DrawCircle(x, y, r float64) { dc.DrawEllipticalArc(x, y, r, r, 0, 2*math.Pi) } +func (dc *Context) DrawImage(im image.Image, x, y int) { + p := image.Pt(x, y) + r := image.Rectangle{p, p.Add(im.Bounds().Size())} + draw.Draw(dc.im, r, im, image.ZP, draw.Src) +} + // Text Functions func (dc *Context) SetFontFace(fontFace font.Face) { diff --git a/examples/tiling.go b/examples/tiling.go new file mode 100644 index 0000000..e95a743 --- /dev/null +++ b/examples/tiling.go @@ -0,0 +1,21 @@ +package main + +import "github.com/fogleman/gg" + +func main() { + const NX = 4 + const NY = 3 + im, err := gg.LoadPNG("examples/gopher.png") + if err != nil { + panic(err) + } + w := im.Bounds().Size().X + h := im.Bounds().Size().Y + dc := gg.NewContext(w*NX, h*NY) + for y := 0; y < NY; y++ { + for x := 0; x < NX; x++ { + dc.DrawImage(im, x*w, y*h) + } + } + dc.WritePNG("out.png") +} diff --git a/util.go b/util.go index 20f0017..61b3dcd 100644 --- a/util.go +++ b/util.go @@ -24,7 +24,16 @@ func Degrees(radians float64) float64 { return radians * 180 / math.Pi } -func writePNG(path string, im image.Image) error { +func LoadPNG(path string) (image.Image, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + return png.Decode(file) +} + +func SavePNG(path string, im image.Image) error { file, err := os.Create(path) if err != nil { return err