// ASCIIArt2SVG converts two-dimensional ASCII art read from r to a SVG // written to w. // xScale denotes the number of pixels to scale each unit on the x-axis to. // yScale denotes the number of pixels to scale each unit on the y-axis to. func ASCIIArt2SVG(w io.Writer, r io.Reader, xScale, yScale float64) error { aa, err := ioutil.ReadAll(r) if err != nil { return err } p := asciiart.NewParser() if err := p.SetScale(xScale, yScale); err != nil { return err } grid, err := p.Parse(string(aa)) if err != nil { return err } if err := svg.Generate(w, grid); err != nil { return err } return nil }
// STARTMAIN OMIT func main() { p := asciiart.NewParser() p.SetScale(1, 1) grid, err := p.Parse(asciiArt) if err != nil { log.Fatal(err) } var traverse func(elems []interface{}, indent string) fmtJsn := func(j map[string]interface{}) string { b, _ := json.Marshal(j); return string(b) } fmtFlt := func(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) } fmt.Println("grid", grid.W, grid.H) // ENDMAIN OMIT // STARTTRAVERSE OMIT traverse = func(elems []interface{}, indent string) { var p []string for _, elem := range elems { switch t := elem.(type) { case *asciiart.Rectangle: fmt.Println(indent, "rect", t.X, t.Y, t.W, t.H, fmtJsn(t.Ref)) traverse(t.Elems, indent+" ") // recursion // HL case *asciiart.Line: fmt.Println(indent, "line", t.X1, t.Y1, t.X2, t.Y2) case *asciiart.Polyline: for i := 0; i < len(t.X); i++ { p = append(p, fmtFlt(t.X[i]), fmtFlt(t.Y[i])) } fmt.Println(indent, "polyline", strings.Join(p, " ")) case *asciiart.Polygon: for i := 0; i < len(t.X); i++ { p = append(p, fmtFlt(t.X[i]), fmtFlt(t.Y[i])) } fmt.Println(indent, "polygon", strings.Join(p, " ")) case *asciiart.Textline: fmt.Println(indent, "textline", t.X, t.Y, t.Text) } } } // ENDTRAVERSE OMIT // STARTMAIN2 OMIT traverse(grid.Elems, " ") }
func TestGenerate(t *testing.T) { p := asciiart.NewParser() fis, err := ioutil.ReadDir("testdata") assert.NoError(t, err) for _, fi := range fis { inFN := fi.Name() if strings.HasSuffix(inFN, ".txt") { input, err := ioutil.ReadFile(filepath.Join("testdata", inFN)) assert.NoError(t, err) g, err := p.Parse(string(input)) assert.NoError(t, err) var svg bytes.Buffer err = Generate(&svg, g) assert.NoError(t, err) outFN := strings.TrimSuffix(inFN, ".txt") + ".svg" output, err := ioutil.ReadFile(filepath.Join("testdata", outFN)) assert.NoError(t, err) assert.Equal(t, string(output), svg.String()) } } }