示例#1
0
func drawFitCentered(c *freetype.Context, text string, img image.Image, bottom bool) {
	lines, longest := splitLines(text)

	// Calculate the font size that fits the longest line within the image width.
	// Simplistic approach -- calculate the width of the line at MaxFontSize, then divide it
	//   down to get the appropriate font size. Not quite right, but close enough.
	size := MaxFontSize
	c.SetFontSize(MaxFontSize)
	fw, _, _ := c.MeasureString(lines[longest])
	w := int(fw >> 8)
	ratio := float64(img.Bounds().Dx()-16) / float64(w)
	size *= ratio
	if size > MaxFontSize {
		size = MaxFontSize
	} else {
		w = int(float64(w) * ratio)
	}
	c.SetFontSize(size)

	pos := 0
	for _, line := range lines {
		fw, _, _ = c.MeasureString(line)
		w := int(fw >> 8)

		lineHeight := int(size * 1.2)
		x := img.Bounds().Dx()/2 - w/2
		y := 0
		if bottom {
			y = img.Bounds().Max.Y - 8 - (len(lines)-1)*lineHeight + pos
		} else {
			y = int(size) + 8 + pos
		}
		pos += lineHeight
		drawBorderedText(c, line, x, y)
	}
}