git.lucas.co / go_mono
git clone https://git.lucas.co/go_mono.git

example/font/main.go (2.4K)

  1 // Copyright 2015 The Go Authors. All rights reserved.
  2 // Use of this source code is governed by a BSD-style
  3 // license that can be found in the LICENSE file.
  4 
  5 //go:build example
  6 // +build example
  7 
  8 // This build tag means that "go install golang.org/x/image/..." doesn't
  9 // install this example program. Use "go run main.go" to run it or "go install
 10 // -tags=example" to install it.
 11 
 12 // Font is a basic example of using fonts.
 13 package main
 14 
 15 import (
 16 	"flag"
 17 	"image"
 18 	"image/color"
 19 	"image/draw"
 20 	"image/png"
 21 	"io/ioutil"
 22 	"log"
 23 	"os"
 24 	"path/filepath"
 25 	"strings"
 26 
 27 	"golang.org/x/image/font"
 28 	"golang.org/x/image/font/plan9font"
 29 	"golang.org/x/image/math/fixed"
 30 )
 31 
 32 var (
 33 	fontFlag = flag.String("font", "",
 34 		`filename of the Plan 9 font or subfont file, such as "lucsans/unicode.8.font" or "lucsans/lsr.14"`)
 35 	firstRuneFlag = flag.Int("firstrune", 0, "the Unicode code point of the first rune in the subfont file")
 36 )
 37 
 38 func pt(p fixed.Point26_6) image.Point {
 39 	return image.Point{
 40 		X: int(p.X+32) >> 6,
 41 		Y: int(p.Y+32) >> 6,
 42 	}
 43 }
 44 
 45 func main() {
 46 	flag.Parse()
 47 
 48 	// TODO: mmap the files.
 49 	if *fontFlag == "" {
 50 		flag.Usage()
 51 		log.Fatal("no font specified")
 52 	}
 53 	var face font.Face
 54 	if strings.HasSuffix(*fontFlag, ".font") {
 55 		fontData, err := ioutil.ReadFile(*fontFlag)
 56 		if err != nil {
 57 			log.Fatal(err)
 58 		}
 59 		dir := filepath.Dir(*fontFlag)
 60 		face, err = plan9font.ParseFont(fontData, func(name string) ([]byte, error) {
 61 			return ioutil.ReadFile(filepath.Join(dir, filepath.FromSlash(name)))
 62 		})
 63 		if err != nil {
 64 			log.Fatal(err)
 65 		}
 66 	} else {
 67 		fontData, err := ioutil.ReadFile(*fontFlag)
 68 		if err != nil {
 69 			log.Fatal(err)
 70 		}
 71 		face, err = plan9font.ParseSubfont(fontData, rune(*firstRuneFlag))
 72 		if err != nil {
 73 			log.Fatal(err)
 74 		}
 75 	}
 76 
 77 	dst := image.NewRGBA(image.Rect(0, 0, 800, 300))
 78 	draw.Draw(dst, dst.Bounds(), image.Black, image.Point{}, draw.Src)
 79 
 80 	d := &font.Drawer{
 81 		Dst:  dst,
 82 		Src:  image.White,
 83 		Face: face,
 84 	}
 85 	ss := []string{
 86 		"The quick brown fox jumps over the lazy dog.",
 87 		"Hello, 世界.",
 88 		"U+FFFD is \ufffd.",
 89 	}
 90 	for i, s := range ss {
 91 		d.Dot = fixed.P(20, 100*i+80)
 92 		dot0 := pt(d.Dot)
 93 		d.DrawString(s)
 94 		dot1 := pt(d.Dot)
 95 		dst.SetRGBA(dot0.X, dot0.Y, color.RGBA{0xff, 0x00, 0x00, 0xff})
 96 		dst.SetRGBA(dot1.X, dot1.Y, color.RGBA{0x00, 0x00, 0xff, 0xff})
 97 	}
 98 
 99 	out, err := os.Create("out.png")
100 	if err != nil {
101 		log.Fatal(err)
102 	}
103 	defer out.Close()
104 	if err := png.Encode(out, dst); err != nil {
105 		log.Fatal(err)
106 	}
107 }