Skip to content

Instantly share code, notes, and snippets.

@hajimehoshi
Created July 3, 2020 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hajimehoshi/9bcc537df341b370a67c6e567f91c08a to your computer and use it in GitHub Desktop.
Save hajimehoshi/9bcc537df341b370a67c6e567f91c08a to your computer and use it in GitHub Desktop.
package main
import (
"image"
"image/color"
"image/draw"
"image/png"
"os"
"strings"
"github.com/pkg/browser"
"golang.org/x/image/font"
"golang.org/x/image/font/opentype"
"golang.org/x/image/font/sfnt"
"golang.org/x/image/math/fixed"
)
func run() error {
width := 640
text := `All 人間 are born 自由 and 平等 in 尊厳 and 権利.`
const (
offsetX = 8
offsetY = 8
)
const (
size = 24
dotX = 4
dotY = 20
glyphWidth = size
glyphHeight = size * 1.5
)
height := glyphHeight*len(strings.Split(strings.TrimSpace(text), "\n")) + offsetX*2
dst := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.ZP, draw.Src)
// I used NotoSerifCJKjp-Regular.otf
otf, err := os.Open("test.otf")
if err != nil {
return err
}
defer otf.Close()
sf, err := sfnt.ParseReaderAt(otf)
if err != nil {
return err
}
f, err := opentype.NewFace(sf, &opentype.FaceOptions{
Size: size,
DPI: 72,
})
if err != nil {
return err
}
d := font.Drawer{
Dst: dst,
Src: image.NewUniform(color.Black),
Face: f,
Dot: fixed.P(dotX+offsetX, dotY+offsetY),
}
for _, l := range strings.Split(text, "\n") {
d.DrawString(l)
d.Dot.X = fixed.I(dotX + offsetX)
d.Dot.Y += f.Metrics().Height
}
path := "example.png"
fout, err := os.Create(path)
if err != nil {
return err
}
defer fout.Close()
if err := png.Encode(fout, d.Dst); err != nil {
return err
}
if err := browser.OpenFile(path); err != nil {
return err
}
return nil
}
func main() {
if err := run(); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment