Example #1
0
// DrawText is a convenience function that will create a new image, render
// the provided text to it, paint the image to the provided window, and resize
// the window to fit the text snugly.
//
// An error can occur when rendering the text to an image.
func DrawText(win *xwindow.Window, font *truetype.Font, size float64,
	fontClr, bgClr render.Color, text string) error {

	// BUG(burntsushi): If `text` is zero-length, very bad things happen.
	if len(text) == 0 {
		text = " "
	}

	// Over estimate the extents.
	ew, eh := xgraphics.Extents(font, size, text)

	// Create an image using the over estimated extents.
	img := xgraphics.New(win.X, image.Rect(0, 0, ew, eh))
	xgraphics.BlendBgColor(img, bgClr.ImageColor())

	// Now draw the text, grab the (x, y) position advanced by the text, and
	// check for an error in rendering.
	_, _, err := img.Text(0, 0, fontClr.ImageColor(), size, font, text)
	if err != nil {
		return err
	}

	// Resize the window to the geometry determined by (x, y).
	win.Resize(ew, eh)

	// Now draw the image to the window and destroy it.
	img.XSurfaceSet(win.Id)
	// subimg := img.SubImage(image.Rect(0, 0, ew, eh))
	img.XDraw()
	img.XPaint(win.Id)
	img.Destroy()

	return nil
}