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

先看效果:git

NewImage

源碼github

package maingolang

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

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

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

// getZWFont 加載字體
func getZWFont() *truetype.Font {源碼

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

    // 讀字體數據
    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
}it

func drawChart() {io

    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")    }}

相關文章
相關標籤/搜索