示例#1
0
文件: glyph.go 项目: runningwild/glop
// Render draws rune r front the specified font at the specified dpi and scale.  It returns a
// grayscale image that is just large enough to contain the rune.
func Render(font *truetype.Font, r rune, dpi, scale float64) (*image.Gray, error) {
	glyph := truetype.NewGlyphBuf()
	index := font.Index(r)
	glyph.Load(font, font.FUnitsPerEm(), index, truetype.FullHinting)
	ctx := freetype.NewContext()
	boxer := makeBoundingBoxer()
	ctx.SetSrc(image.NewUniform(color.White))
	ctx.SetDst(boxer)
	ctx.SetClip(boxer.largeBounds)
	ctx.SetFontSize(250)
	ctx.SetDPI(dpi)
	ctx.SetFont(font)
	if err := glyph.Load(font, font.FUnitsPerEm(), font.Index(r), truetype.FullHinting); err != nil {
		return nil, fmt.Errorf("Unable to load glyph: %v\n", err)
	}
	var rp raster.Point
	rp.X = ctx.PointToFix32(0)
	rp.Y = ctx.PointToFix32(100)
	ctx.DrawString(string(r), rp)
	boxer.complete()

	g := gift.New(
		gift.Resize(int(float64(boxer.Bounds().Dx())*scale+0.5), int(float64(boxer.Bounds().Dy())*scale+0.5), gift.CubicResampling),
	)
	dst := image.NewGray(g.Bounds(boxer.Bounds()))
	g.Draw(dst, boxer)
	return dst, nil
}