zoukankan      html  css  js  c++  java
  • wcharczuk/go-chart图表上使用中文字体

    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

  • 相关阅读:
    python_网络编程struct模块解决黏包问题
    python_网络编程socket(UDP)
    python_网络编程socket(TCP)
    python_面向对象
    python_生成器
    python_迭代器
    linux实操_shell自定义函数
    linux实操_shell系统函数
    linux实操_shell读取控制台输入
    scrapy-redis 0.6.8 配置信息
  • 原文地址:https://www.cnblogs.com/ghj1976/p/11356025.html
Copyright © 2011-2022 走看看