Created
April 13, 2020 12:13
-
-
Save hajimehoshi/61efcf26d603cef46bf4fabab3b51196 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 human beings are born free and equal in dignity and rights.` | |
const ( | |
offsetX = 8 | |
offsetY = 8 | |
) | |
const ( | |
size = 72 | |
dotX = 4 | |
dotY = 12 | |
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