func TestSampleHelloWorld(t *testing.T) { // Set the global folder for searching fonts // The pdf backend needs for every ttf file its corresponding // json/.z file which is generated by gofpdf/makefont. draw2d.SetFontFolder("../resource/font") test(t, helloworld.Main) }
// setupDraw2D ensure Draw2D can find its fonts. func setupDraw2D() { p, err := build.Default.Import("github.com/llgcode/draw2d", "", build.FindOnly) if err != nil { log.Fatalf("Couldn't find llgcode/draw2d files: %v", err) } draw2d.SetFontFolder(filepath.Join(p.Dir, "resource", "font")) }
func (r *Renderer) Draw() image.Image { pixelsX, pixelsY := int(r.width), int(r.height) dest := image.NewRGBA(image.Rect(0, 0, pixelsX, pixelsY)) draw.Draw(dest, dest.Bounds(), &image.Uniform{r.m.BgColor}, image.ZP, draw.Src) draw2d.SetFontFolder("/Library/Fonts/") draw2d.SetFontNamer(func(fontData draw2d.FontData) string { return fontData.Name + ".ttf" }) gc := draw2dimg.NewGraphicContext(dest) // gc.DPI = 300 gc.SetLineCap(draw2d.RoundCap) gc.SetFillColor(r.m.BgColor) gc.SetStrokeColor(r.m.Stroke) gc.SetFontData(draw2d.FontData{Name: "Georgia", Family: draw2d.FontFamilySerif, Style: draw2d.FontStyleNormal}) dx := math.Abs(r.bbox[2] - r.bbox[0]) dy := math.Abs(r.bbox[3] - r.bbox[1]) pxf, pyf := float64(pixelsX), float64(pixelsY) r1, r2 := (pxf / dx), (pyf / dy) r0 := math.Min(r1, r2) w, h := dx*r0, dy*r0 ox, oy := (pxf-w)/2, (pyf-h)/2 img_box := [4]float64{ox, oy, ox + w, oy + h} r.matrix = draw2d.NewMatrixFromRects(r.bbox, img_box) for _, layer := range r.m.Layers { q := query.NewQuery(r.m.Bounds()).Select(layer.SourceQuery()) if ds := layer.LoadSource(); ds != nil { defer ds.Close() for shp := range ds.Query(q) { var symbolizerType util.SymbolizerType switch shp.(type) { case geom.LineShape, geom.MultiLineShape: symbolizerType = util.PathType case geom.PolygonShape: symbolizerType = util.PolygonType } for _, symbolizer := range r.findSymbolizers(layer, symbolizerType) { symbolizer.Draw(gc, shp) } for _, symbolizer := range r.findSymbolizers(layer, util.TextType) { symbolizer.Draw(gc, shp) } } } } return dest }
func measureText(fontSize float64, text string) (width, height float64) { dest := image.NewRGBA(image.Rect(0, 0, 1, 1)) ctx := draw2dimg.NewGraphicContext(dest) fontData := draw2d.FontData{ Name: "Roboto", Family: draw2d.FontFamilySans, Style: draw2d.FontStyleNormal, } draw2d.SetFontFolder(fontFolder()) ctx.SetFontData(fontData) ctx.SetFontSize(fontSize) left, top, right, bottom := ctx.GetStringBounds(text) width = right - left height = bottom - top return }
func generateCaptionImage(width int, fontSize float64, caption string) image.Image { lines := wrapText(fontSize, caption, float64(width)*(1-captionSideMargin*2)) height := wrappedTextHeight(fontSize, lines) dest := image.NewRGBA(image.Rect(0, 0, width, int(height))) ctx := draw2dimg.NewGraphicContext(dest) draw2d.SetFontFolder(fontFolder()) ctx.SetFontData(defaultFontData) ctx.SetFontSize(fontSize) ctx.SetFillColor(color.RGBA{0, 0, 0, 255}) var y float64 for _, line := range lines { lineWidth, lineHeight := measureText(fontSize, line) lineMargin := lineHeight * (lineHeightRatio - 1) / 2 y += lineHeight + lineMargin ctx.FillStringAt(line, (float64(width)-lineWidth)/2, y) y += lineMargin } return dest }
// Draw "Hello World" func DrawHello(gc draw2d.GraphicContext, text string) { draw2d.SetFontFolder("static") gc.SetFontData(draw2d.FontData{ Name: "Roboto", }) gc.SetFontSize(14) l, t, r, b := gc.GetStringBounds(text) //log.Println(t, l, r, b) draw2dkit.Rectangle(gc, 0, 0, r-l+30, b-t+30) gc.SetFillColor(image.White) gc.FillStroke() draw2dkit.Rectangle(gc, 10, 10, r-l+20, b-t+20) gc.SetFillColor(image.White) gc.FillStroke() gc.SetFillColor(color.NRGBA{R: 255, G: 0, B: 0, A: 255}) gc.FillStringAt(text, 15-l, 15-t) }
func DrawGrid(v *Viewport, fileName string) { log.Println("DRAWING GRID FOR", v.ULCorner, v.LRCorner) draw2d.SetFontFolder("") dest := image.NewRGBA(image.Rect(0, 0, 400, 400)) white := color.RGBA{0xff, 0xff, 0xff, 255} draw.Draw(dest, dest.Bounds(), &image.Uniform{white}, image.ZP, draw.Src) gc := draw2dimg.NewGraphicContext(dest) gc.SetFontData(draw2d.FontData{Name: "DroidSansMono", Family: draw2d.FontFamilyMono}) gc.SetFillColor(image.Black) gc.SetFontSize(8) for x := 0; x < 400; x++ { for y := 0; y < 400; y++ { p := Pixel{float64(x), float64(y)} hex := v.HexContaining(p) var clr color.RGBA clN := (hex[0] - hex[1]) % 4 for clN < 0 { clN += 4 } switch clN { case 0: // blue clr = color.RGBA{0x33, 0x66, 0xcc, 255} case 1: // green clr = color.RGBA{0x00, 0xAA, 0x33, 255} case 2: // red clr = color.RGBA{0xAA, 0x33, 0x33, 255} default: // white clr = white } dest.Set(x, y, clr) /*if (x+60)%60 == 0 && y%15 == 0 { gc.FillStringAt(fmt.Sprintf("(%d,%d)", hex[0], hex[1]), p[0], p[1]) }*/ } } for _, h := range v.VisList() { corners := v.CornersOf(h) gc.MoveTo(corners[0][0], corners[0][1]) for i, _ := range corners { var px, py float64 if i == 5 { px, py = corners[0][0], corners[0][1] } else { px, py = corners[i+1][0], corners[i+1][1] } gc.LineTo(px, py) } gc.Close() gc.Stroke() c := v.CenterOf(h) gc.FillStringAt(fmt.Sprintf("(%d,%d)", h[0], h[1]), c[0], c[1]) } gc.SetLineWidth(2) gc.MoveTo(v.ULCorner[0], v.ULCorner[1]) gc.LineTo(v.LRCorner[0], v.ULCorner[1]) gc.LineTo(v.LRCorner[0], v.LRCorner[1]) gc.LineTo(v.ULCorner[0], v.LRCorner[1]) gc.Close() gc.Stroke() //} draw2dimg.SaveToPngFile(fileName, dest) }
func main() { // Command-line input var in string var height int var col1 string var col2 string flag.StringVar(&in, "f", "", `File to be parsed. The file has to have a certain format. Every line should be "a>b>amount".`) flag.IntVar(&height, "h", 1980, `Height of the output image. The width is deduced from the height.`) flag.StringVar(&col1, "c1", "#eeef61", "Start color of the gradient.") flag.StringVar(&col2, "c2", "#1e3140", "End color of the gradient.") flag.Parse() // Parse the arcgo file names, counter := OpenArcgoFile(in) // Comoute width width := float64(height) * math.Phi * 1.2 // Where the first name is located top := float64(height) / 10 // Where the last name is located bottom := float64(height) - top // Rescale the counter based on the maximal value counter = AssignWidths(counter, 1.0, 20.0) // Assign linearly separated coordinates to each name coordinates := AssignCoordinates(names, top, bottom) // Assign "linearly separated" colors to each name colors := AssignColors(names, col1, col2) // Initialize the image img := image.NewRGBA(image.Rect(0, 0, int(width), height)) gc := draw2dimg.NewGraphicContext(img) // Define the x coordinates for the arcs xRight := float64(width) * 1.7 / 3.0 xLeft := float64(width) * 1.3 / 3.0 // Graph the arcs for a := range counter { // Get the color of the name gc.SetStrokeColor(colors[a]) for b := range counter[a] { // Set where the arc begins y1 := coordinates[a] // Set where the arc ends y2 := coordinates[b] // Set the width of the arc z := counter[a][b] gc.SetLineWidth(2 * z) // Define on what side the arc is if y1 < y2 { // Right side arc Arc(gc, xRight, y1, y2) } else { // Left side arc Arc(gc, xLeft, y1, y2) } } } // Set the font for writing the names draw2d.SetFontFolder("") gc.SetFontData(draw2d.FontData{Name: "coolvetica"}) gc.SetFillColor(image.Black) fontSize := float64(height / (3 * len(names))) gc.SetFontSize(fontSize) // Write the names for _, name := range names { x := width/2.0 - (float64(len(name))*fontSize)/3.8 y := coordinates[name] + fontSize/2 - 2 gc.FillStringAt(name, x, y) } // Save to file path := strings.Split(in, "/") out := strings.Join([]string{strings.Split(path[len(path)-1], ".")[0], "png"}, ".") draw2dimg.SaveToPngFile(out, img) }
func genTwitterGif(tweets []anaconda.Tweet, username string, tid int64) (string, error) { wid := 440 height := 220 colList := color.Palette{ color.RGBA{0x00, 0x00, 0x00, 0xFF}, color.RGBA{0xFF, 0x33, 0x33, 0xFF}, color.RGBA{0x33, 0xFF, 0x33, 0xFF}, color.RGBA{0x33, 0x33, 0xFF, 0xFF}, color.RGBA{0xFF, 0xFF, 0x33, 0xFF}, color.RGBA{0xFF, 0x33, 0xFF, 0xFF}, color.RGBA{0x33, 0xFF, 0xFF, 0xFF}, } newList := []*image.Paletted{} delayList := []int{} fireworkList := []FireWork{} disposalList := []byte{} draw2d.SetFontFolder("static") for i := range tweets { f := genFireworkFromTweet(tweets, i, float64(wid), float64(height)) fireworkList = append(fireworkList, f) } boundRect := image.Rect(0, 0, wid, height) for len(fireworkList) > 0 { rawImg := image.NewRGBA(boundRect) // TODO :: Create Custom Painter // which does blend up painter := raster.NewRGBAPainter(rawImg) gc := draw2dimg.NewGraphicContextWithPainter(rawImg, painter) gc.SetFontData(draw2d.FontData{ Name: "Roboto", }) gc.SetFontSize(8) gc.Clear() gc.SetFillColor(colList[0]) gc.MoveTo(0, 0) gc.LineTo(0, float64(height)) gc.LineTo(float64(wid), float64(height)) gc.LineTo(float64(wid), 0) gc.Close() gc.Fill() newFList := []FireWork{} for _, f := range fireworkList { if f.d > 0 { f.d -= 1.0 } else { gc.SetFillColor(colList[f.colID]) gc.SetStrokeColor(colList[f.colID]) gc.MoveTo(f.x, f.y) gc.FillStringAt(f.text, f.x-4, f.y+4) gc.MoveTo(f.x, f.y) gc.SetLineWidth(f.sz) gc.LineTo(f.x-f.dx, f.y-f.dy) for ns := 1.0; ns < f.sz; ns += 1.0 { gc.SetLineWidth(f.sz - ns) gc.LineTo(f.x-f.dx*ns*0.2, f.y-f.dy*ns*0.2) } gc.Stroke() f.x += f.dx f.y += f.dy f.t -= 1.0 f.dy += 0.3 } if f.t > 0 { newFList = append(newFList, f) } else if len(f.bundle) > 0 { for _, subF := range f.bundle { subF.x += f.x subF.y += f.y newFList = append(newFList, subF) } } } fireworkList = newFList // Make Pallette Image newImg := image.NewPaletted(boundRect, colList) for x := 0; x < wid; x++ { for y := 0; y < height; y++ { newImg.SetColorIndex(x, y, uint8(colList.Index(rawImg.At(x, y)))) } } // Add Lists if len(newList) == 0 { disposalList = append(disposalList, gif.DisposalNone) } else { disposalList = append(disposalList, gif.DisposalPrevious) } newList = append(newList, newImg) delayList = append(delayList, 10) } log.Println("Saving gif with ", len(newList), " frames") gifData := gif.GIF{ Image: newList, Delay: delayList, Disposal: disposalList, LoopCount: -1, BackgroundIndex: 0, Config: image.Config{ ColorModel: colList, Width: wid, Height: height, }, } fn := MakeGifFilename(username, tid) f, e := os.Create(fn) if e != nil { log.Println(e) return "", e } e = gif.EncodeAll(f, &gifData) if e != nil { log.Println(e) return "", e } return fn, nil }
func (cfg *Config) init() error { if cfg.inited { return nil } var err error if redisAddressFlag.Value() != "" { cfg.rpool.Dial = func() (redis.Conn, error) { c, err := redis.Dial("tcp", redisAddressFlag.Value()) if err != nil { return nil, err } if redisPasswordFlag.Value() != "" { if _, err := c.Do("AUTH", redisPasswordFlag.Value()); err != nil { c.Close() return nil, err } } return c, nil } cfg.rpool.MaxIdle = 2 } cfg.statusChan = make(chan string, 8) cfg.criterion = health.NewCriterion("web.ok", false) if cfg.HTTPServer.Server == nil { cfg.HTTPServer.Server = &http.Server{} } if cfg.HTTPServer.Addr == "" { cfg.HTTPServer.Addr = bindFlag.Value() } if cfg.SessionConfig == nil { cfg.SessionConfig = &session.Config{} } if cfg.SessionConfig.CookieName == "" { cfg.SessionConfig.CookieName = "s" } if len(cfg.SessionConfig.SecretKey) == 0 { cfg.SessionConfig.SecretKey = opts.VariantSecretKey("cookie-secret-key") } if cfg.SessionConfig.Store == nil { var redisStore storage.Store if redisAddressFlag.Value() != "" { if redisPrefixFlag.Value() == "" { return fmt.Errorf("must specify a redis prefix") } redisStore, err = redissession.New(redissession.Config{ Prefix: redisPrefixFlag.Value() + "s/", GetConn: func() (redis.Conn, error) { c := cfg.rpool.Get() if c == nil { return nil, fmt.Errorf("cannot get redis") } return c, nil }, }) if err != nil { return err } } cfg.SessionConfig.Store, err = memorysession.New(memorysession.Config{ FallbackStore: redisStore, }) if err != nil { return err } } draw2d.SetFontFolder(filepath.Join(opts.BaseDir, "assets/fonts")) err = tpl.LoadTemplates(filepath.Join(opts.BaseDir, "tpl")) if err != nil { return err } bstaticName := "bstatic" if !opts.DevMode { bstaticName = "bstatic.rel" } assetmgr.Default, err = assetmgr.New(assetmgr.Config{ Path: filepath.Join(opts.BaseDir, bstaticName), }) if err != nil { return err } Router.HandleFunc("/{page}", Front_GET).Methods("GET") Router.HandleFunc("/", Front_GET).Methods("GET") cfg.inited = true return nil }
func TestSampleHelloWorld(t *testing.T) { // Set the global folder for searching fonts draw2d.SetFontFolder("resource/font") test(t, helloworld.Main) }
func init() { draw2d.SetFontFolder("./static") }