From 8ed9c9d86270f909e266b118da87367b6bcf45e3 Mon Sep 17 00:00:00 2001 From: Michael Fogleman Date: Fri, 19 Feb 2016 21:35:56 -0500 Subject: [PATCH] anchored functions --- README.md | 4 +++- context.go | 18 ++++++++++++++++-- examples/ellipse.go | 4 +--- examples/text.go | 14 ++++---------- 4 files changed, 24 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 585f35c..146b943 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,9 @@ DrawArc(x, y, r, angle1, angle2 float64) DrawEllipse(x, y, rx, ry float64) DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64) DrawImage(im image.Image, x, y int) -DrawString(x, y float64, s string) +DrawImageAnchored(im image.Image, x, y int, ax, ay float64) +DrawString(s string, x, y float64) +DrawStringAnchored(s string, x, y, ax, ay float64) MoveTo(x, y float64) LineTo(x, y float64) diff --git a/context.go b/context.go index 041d200..4f65f71 100644 --- a/context.go +++ b/context.go @@ -323,8 +323,15 @@ func (dc *Context) DrawCircle(x, y, r float64) { } func (dc *Context) DrawImage(im image.Image, x, y int) { + dc.DrawImageAnchored(im, x, y, 0, 0) +} + +func (dc *Context) DrawImageAnchored(im image.Image, x, y int, ax, ay float64) { + s := im.Bounds().Size() + x -= int(ax * float64(s.X)) + y -= int(ay * float64(s.Y)) p := image.Pt(x, y) - r := image.Rectangle{p, p.Add(im.Bounds().Size())} + r := image.Rectangle{p, p.Add(s)} draw.Draw(dc.im, r, im, image.ZP, draw.Over) } @@ -339,7 +346,14 @@ func (dc *Context) LoadFontFace(path string, points float64) { dc.fontHeight = points * 72 / 96 } -func (dc *Context) DrawString(x, y float64, s string) { +func (dc *Context) DrawString(s string, x, y float64) { + dc.DrawStringAnchored(s, x, y, 0, 0) +} + +func (dc *Context) DrawStringAnchored(s string, x, y, ax, ay float64) { + w, h := dc.MeasureString(s) + x -= ax * w + y += ay * h x, y = dc.TransformPoint(x, y) d := &font.Drawer{ Dst: dc.im, diff --git a/examples/ellipse.go b/examples/ellipse.go index abe6518..bb46543 100644 --- a/examples/ellipse.go +++ b/examples/ellipse.go @@ -14,9 +14,7 @@ func main() { dc.Pop() } if im, err := gg.LoadPNG("examples/gopher.png"); err == nil { - w := im.Bounds().Size().X - h := im.Bounds().Size().Y - dc.DrawImage(im, S/2-w/2, S/2-h/2) + dc.DrawImageAnchored(im, S/2, S/2, 0.5, 0.5) } dc.SavePNG("out.png") } diff --git a/examples/text.go b/examples/text.go index 2d713db..273cddd 100644 --- a/examples/text.go +++ b/examples/text.go @@ -1,20 +1,14 @@ package main -import ( - "fmt" - - "github.com/fogleman/gg" -) +import "github.com/fogleman/gg" func main() { - dc := gg.NewContext(1000, 1000) + const S = 1024 + dc := gg.NewContext(S, S) dc.SetRGB(1, 1, 1) dc.Clear() dc.SetRGB(0, 0, 0) dc.LoadFontFace("/Library/Fonts/Arial.ttf", 96) - s := "Hello, world!" - w, h := dc.MeasureString(s) - fmt.Println(w, h) - dc.DrawString(500-w/2, 500+h/2, s) + dc.DrawStringAnchored("Hello, world!", S/2, S/2, 0.5, 0.5) dc.SavePNG("out.png") }