diff --git a/context.go b/context.go index dfbcb5a..dada847 100644 --- a/context.go +++ b/context.go @@ -7,6 +7,8 @@ import ( "math" "github.com/golang/freetype/raster" + "golang.org/x/image/font" + "golang.org/x/image/font/basicfont" "golang.org/x/image/math/fixed" ) @@ -43,6 +45,7 @@ type Context struct { capper raster.Capper joiner raster.Joiner fillRule FillRule + fontFace font.Face } func NewContext(width, height int) *Context { @@ -54,6 +57,7 @@ func NewContext(width, height int) *Context { color: color.Transparent, lineWidth: 1, fillRule: FillRuleWinding, + fontFace: basicfont.Face7x13, } } @@ -181,6 +185,8 @@ func (dc *Context) Fill() { dc.NewPath() } +// Convenient Drawing Functions + func (dc *Context) DrawLine(x1, y1, x2, y2 float64) { dc.MoveTo(x1, y1) dc.LineTo(x2, y2) @@ -219,3 +225,33 @@ func (dc *Context) DrawArc(x, y, r, angle1, angle2 float64) { func (dc *Context) DrawCircle(x, y, r float64) { dc.DrawEllipseArc(x, y, r, r, 0, 2*math.Pi) } + +// Text Functions + +func (dc *Context) SetFontFace(fontFace font.Face) { + dc.fontFace = fontFace +} + +func (dc *Context) LoadFontFace(path string, size float64) { + dc.fontFace = loadFontFace(path, size) +} + +func (dc *Context) DrawString(x, y float64, s string) { + d := &font.Drawer{ + Dst: dc.im, + Src: image.NewUniform(dc.color), + Face: dc.fontFace, + Dot: fp(x, y), + } + d.DrawString(s) +} + +func (dc *Context) MeasureString(s string) float64 { + d := &font.Drawer{ + Dst: nil, + Src: nil, + Face: dc.fontFace, + } + a := d.MeasureString(s) + return float64(a >> 6) +} diff --git a/examples/text.go b/examples/text.go new file mode 100644 index 0000000..614f941 --- /dev/null +++ b/examples/text.go @@ -0,0 +1,15 @@ +package main + +import "github.com/fogleman/dd" + +func main() { + dc := dd.NewContext(1000, 1000) + dc.SetSourceRGB(1, 1, 1) + dc.Paint() + dc.SetSourceRGB(0, 0, 0) + dc.LoadFontFace("/Library/Fonts/Impact.ttf", 96) + s := "Hello, world!" + w := dc.MeasureString(s) + dc.DrawString(500-w/2, 500, s) + dc.WriteToPNG("out.png") +} diff --git a/util.go b/util.go index 0d9611e..e146eda 100644 --- a/util.go +++ b/util.go @@ -3,8 +3,12 @@ package dd import ( "image" "image/png" + "io/ioutil" "os" + "github.com/golang/freetype/truetype" + + "golang.org/x/image/font" "golang.org/x/image/math/fixed" ) @@ -24,3 +28,19 @@ func fp(x, y float64) fixed.Point26_6 { func fi(x float64) fixed.Int26_6 { return fixed.Int26_6(x * 64) } + +func loadFontFace(path string, size float64) font.Face { + fontBytes, err := ioutil.ReadFile(path) + if err != nil { + panic(err) + } + f, err := truetype.Parse(fontBytes) + if err != nil { + panic(err) + } + return truetype.NewFace(f, &truetype.Options{ + Size: size, + DPI: 96, + Hinting: font.HintingFull, + }) +}