导航

wcharczuk/go-chart图表上使用中文字体

Posted on 2019-08-15 09:35  蝈蝈俊  阅读(2033)  评论(2编辑  收藏  举报

https://github.com/wcharczuk/go-chart/ 默认使用的字体是 roboto.Roboto,不支持中文。 


// GetDefaultFont returns the default font (Roboto-Medium).
func GetDefaultFont() (*truetype.Font, error) {
    if _defaultFont == nil {
        _defaultFontLock.Lock()
        defer _defaultFontLock.Unlock()
        if _defaultFont == nil {
            font, err := truetype.Parse(roboto.Roboto)
            if err != nil {
                return nil, err
            }
            _defaultFont = font
        }
    }
    return _defaultFont, nil
}

 

当图表上需要显示中文字体时就会显示成 X 。 如下图

NewImage

这时候就要中自己的中文字体了。 下面是使用的一个简单例子。

package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "os"

    "github.com/golang/freetype/truetype"
    "github.com/wcharczuk/go-chart"
    "github.com/wcharczuk/go-chart/drawing"
)

// getZWFont 加载字体
func getZWFont() *truetype.Font {

    fontFile := "/Library/Fonts/Microsoft-YaHei.ttf"
    //fontFile := "/Library/Fonts/AppleMyungjo.ttf"

    // 读字体数据
    fontBytes, err := ioutil.ReadFile(fontFile)
    if err != nil {
        log.Println(err)
        return nil
    }
    font, err := truetype.Parse(fontBytes)
    if err != nil {
        log.Println(err)
        return nil
    }
    return font
}

func drawChart() {
    //f, _ := chart.GetDefaultFont() // 自带默认字体
    f := getZWFont() // 用自己的字体
    r, _ := chart.PNG(1024, 1024)

    chart.Draw.Text(r, "Te郭红俊多多岛ddd", 64, 64, chart.Style{
        FontColor: drawing.ColorBlack,
        FontSize: 18,
        Font: f,
    })

    buffer := bytes.NewBuffer([]byte{})
    r.Save(buffer)

    fo, err := os.Create("o1.png")
    if err != nil {
        panic(err)
    }

    if _, err := fo.Write(buffer.Bytes()); err != nil {
        panic(err)
    }
}

func main() {
    drawChart()
}

 

执行生成的图片效果如下:

NewImage