5 GettingStarted
Laurent Le Goff edited this page 2015-04-19 23:31:18 +02:00

Draw2d Hello World, initialize a graphic context and save the to a png file.

package main

import (
        "bufio"
        "fmt"
        "log"
        "os"

        "github/llgcode/draw2d"
        "image"
        "image/png"
)


func main() {
    // Create a 200x200 RGBA image  
    img := image.NewRGBA(image.Rect(0, 0, 200, 200))
    // Initialize a graphic context on this image
    gc := draw2d.NewGraphicContext(img)
    // Create a new path 
    gc.BeginPath()
    // start the path at (10, 10)
    gc.MoveTo(10.0, 10.0)
    // add a lineto the path to (100.0, 10.0)
    gc.LineTo(100.0, 10.0)
    // Stroke
    gc.Stroke()
    // Save image to disk 
    filePath := "TestGettingStarted.png"
    saveToPngFile(filePath, img)
    fmt.Printf("Wrote %s OK.\n", filePath)
}

// Save image to a file path using PNG format
func saveToPngFile(filePath string, m image.Image) error {
    // Create the file
    f, err := os.Create(filePath)
    if err != nil {
        return err
    }
    defer f.Close()
    // Create Writer from file
    b := bufio.NewWriter(f)
    // Write the image into the buffer
    err = png.Encode(b, m)
    if err != nil {
        return err
    }
    err = b.Flush()
    if err != nil {
        return err
    }
    return nil
}



See Samples to go further.