posts - 496, comments - 190, trackbacks - 0, articles - 0

导航

在wcharczuk/go-chart图表上打印文字

Posted on 2019-08-16 14:30 蝈蝈俊 阅读(...) 评论(...) 编辑 收藏

先看效果:

NewImage

源码

package main

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

    "github.com/wcharczuk/go-chart/drawing"

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

// 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() {

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

    graph := chart.Chart{
        Series: []chart.Series{
            chart.ContinuousSeries{
                XValues: []float64{1.0, 2.0, 3.0, 4.0, 5.0},
                YValues: []float64{1.0, 2.0, 3.0, 4.0, 5.0},
            },
            chart.AnnotationSeries{
                Annotations: []chart.Value2{
                    {XValue: 1.0, YValue: 1.0, Label: "One11"},
                    {XValue: 2.0, YValue: 2.0, Label: "Two"},
                    {XValue: 3.0, YValue: 3.0, Label: "Three"},
                    {XValue: 4.0, YValue: 4.0, Label: "Four"},
                    {XValue: 5.0, YValue: 5.0, Label: "Five"},
                },
            },
        },
        Font: getZWFont(),
        Elements: []chart.Renderable{
            TextInfo([]string{"test郭红俊yyy", "dddwf分发给ff"}),
        },
    }
    err := graph.Render(chart.PNG, buffer)
    if err != nil {
        log.Fatal(err)
    }

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

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

func main() {
    drawChart()
}

// TextInfo 显示文字
func TextInfo(txtArr []string) chart.Renderable {
    return func(r chart.Renderer, cb chart.Box, chartDefaults chart.Style) {
        log.Println(fmt.Sprintf("h:%d; w:%d", cb.Height(), cb.Width()))
        log.Println(chartDefaults)
        log.Println(cb)

        r.SetFont(getZWFont())
        r.SetFontColor(drawing.ColorBlue)
        r.SetFontSize(14)
        i := 0
        for _, txt := range txtArr {
            r.Text(txt, 60+i*10, 40+i*30)
            i++
        }
        log.Println("12444")
    }
}