package sprite import ( "fmt" "io" ) // WriteSVG encodes g as an SVG where each horizontal run of same-colored // pixels becomes one . shape-rendering="crispEdges" keeps the pixel // look at any zoom. scale only affects the document width/height; the // viewBox stays in pixel units. func WriteSVG(w io.Writer, g PixelGrid, scale int) error { if scale < 1 { scale = 1 } gw, gh := g.Bounds() _, err := fmt.Fprintf(w, ``+"\n", gw*scale, gh*scale, gw, gh) if err != nil { return err } for y := 0; y < gh; y++ { for x := 0; x < gw; { c := g.At(x, y) run := 1 for x+run < gw && g.At(x+run, y) == c { run++ } if c.A > 0 { opacity := "" if c.A < 255 { opacity = fmt.Sprintf(` fill-opacity="%.3f"`, float64(c.A)/255) } _, err = fmt.Fprintf(w, ``+"\n", x, y, run, c.R, c.G, c.B, opacity) if err != nil { return err } } x += run } } _, err = io.WriteString(w, "\n") return err }