Example #1
0
func (te *TextElement) getContext() *freetype.Context {
	c := freetype.NewContext()
	c.SetDPI(75)
	c.SetFont(te.props.textFont)
	c.SetFontSize(float64(te.props.textSize))
	c.SetSrc(image.NewUniform(te.props.textColor))
	c.SetHinting(font.HintingNone)
	return c
}
Example #2
0
func main() {
	flag.Parse()

	// Read the font data.
	fontBytes, err := ioutil.ReadFile(*fontfile)
	if err != nil {
		log.Println(err)
		return
	}
	f, err := freetype.ParseFont(fontBytes)
	if err != nil {
		log.Println(err)
		return
	}

	// Initialize the context.
	fg, bg := image.Black, image.White
	if *wonb {
		fg, bg = image.White, image.Black
	}
	c := freetype.NewContext()
	c.SetDPI(*dpi)
	c.SetFont(f)
	c.SetFontSize(*size)
	c.SetSrc(fg)
	switch *hinting {
	default:
		c.SetHinting(font.HintingNone)
	case "full":
		c.SetHinting(font.HintingFull)
	}

	var width fixed.Int26_6
	var height fixed.Int26_6
	for _, s := range text {
		dimensions, _ := c.StringDimensions(s)
		height = height + dimensions.Y
		if dimensions.X > width {
			width = dimensions.X
		}
	}
	imgWidth := int(width >> 6)
	imgHeight := int(height >> 6)
	fmt.Println(imgWidth, imgHeight)
	rgba := image.NewRGBA(image.Rect(0, 0, imgWidth, imgHeight))
	draw.Draw(rgba, rgba.Bounds(), bg, image.ZP, draw.Src)
	c.SetClip(rgba.Bounds())
	c.SetDst(rgba)

	// Draw the text.
	pt := freetype.Pt(0, int(c.PointToFixed(*size)>>6))
	for _, s := range text {
		_, err = c.DrawString(s, pt)
		if err != nil {
			log.Println(err)
			return
		}
		pt.Y += c.PointToFixed(*size * *spacing)
	}

	// Save that RGBA image to disk.
	outFile, err := os.Create("out.png")
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	defer outFile.Close()
	b := bufio.NewWriter(outFile)
	err = png.Encode(b, rgba)
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	err = b.Flush()
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}
	fmt.Println("Wrote out.png OK.")
}