/** * Create a new Graphic context from an image */ func NewGraphicContext(img draw.Image) *ImageGraphicContext { var painter Painter switch selectImage := img.(type) { case *image.RGBA: painter = raster.NewRGBAPainter(selectImage) //case *image.NRGBA: // painter = NewNRGBAPainter(selectImage) default: panic("Image type not supported") } width, height := img.Bounds().Dx(), img.Bounds().Dy() dpi := 92 ftContext := freetype.NewContext() ftContext.SetDPI(dpi) ftContext.SetClip(img.Bounds()) ftContext.SetDst(img) gc := &ImageGraphicContext{ NewStackGraphicContext(), img, painter, raster.NewRasterizer(width, height), raster.NewRasterizer(width, height), ftContext, dpi, } return gc }
// NewGraphicContext creates a new Graphic context from an image. func NewGraphicContext(width, height int) *GraphicContext { gc := &GraphicContext{ draw2d.NewStackGraphicContext(), NewPainter(), raster.NewRasterizer(width, height), raster.NewRasterizer(width, height), } return gc }
// NewGraphicContextWithPainter creates a new Graphic context from an image and a Painter (see Freetype-go) func NewGraphicContextWithPainter(img draw.Image, painter Painter) *ImageGraphicContext { width, height := img.Bounds().Dx(), img.Bounds().Dy() dpi := 92 gc := &ImageGraphicContext{ NewStackGraphicContext(), img, painter, raster.NewRasterizer(width, height), raster.NewRasterizer(width, height), truetype.NewGlyphBuf(), dpi, } return gc }
func TestFreetypeNonZeroWinding(t *testing.T) { var p Path p.LineTo(10, 190) c := curve.CubicCurveFloat64{10, 190, 10, 10, 190, 10, 190, 190} c.Segment(&p, flatteningThreshold) poly := Polygon(p.points) color := color.RGBA{0, 0, 0, 0xff} img := image.NewRGBA(image.Rect(0, 0, 200, 200)) rasterizer := raster.NewRasterizer(200, 200) rasterizer.UseNonZeroWinding = true rasterizer.Start(raster.Point{ X: raster.Fix32(10 * 256), Y: raster.Fix32(190 * 256)}) for j := 0; j < len(poly); j = j + 2 { rasterizer.Add1(raster.Point{ X: raster.Fix32(poly[j] * 256), Y: raster.Fix32(poly[j+1] * 256)}) } painter := raster.NewRGBAPainter(img) painter.SetColor(color) rasterizer.Rasterize(painter) savepng("../output/raster/TestFreetypeNonZeroWinding.png", img) }
func BenchmarkFreetype(b *testing.B) { var p Path p.LineTo(10, 190) c := curve.CubicCurveFloat64{10, 190, 10, 10, 190, 10, 190, 190} c.Segment(&p, flatteningThreshold) poly := Polygon(p.points) color := color.RGBA{0, 0, 0, 0xff} for i := 0; i < b.N; i++ { img := image.NewRGBA(image.Rect(0, 0, 200, 200)) rasterizer := raster.NewRasterizer(200, 200) rasterizer.UseNonZeroWinding = false rasterizer.Start(raster.Point{ X: raster.Fix32(10 * 256), Y: raster.Fix32(190 * 256)}) for j := 0; j < len(poly); j = j + 2 { rasterizer.Add1(raster.Point{ X: raster.Fix32(poly[j] * 256), Y: raster.Fix32(poly[j+1] * 256)}) } painter := raster.NewRGBAPainter(img) painter.SetColor(color) rasterizer.Rasterize(painter) } }
func TestFreetypeRasterizerNonZeroWinding(t *testing.T) { var p Path p.LineTo(10, 190) draw2dbase.TraceCubic(&p, []float64{10, 190, 10, 10, 190, 10, 190, 190}, 0.5) poly := Polygon(p.points) color := color.RGBA{0, 0, 0, 0xff} img := image.NewRGBA(image.Rect(0, 0, 200, 200)) rasterizer := raster.NewRasterizer(200, 200) rasterizer.UseNonZeroWinding = true rasterizer.Start(raster.Point{ X: raster.Fix32(10 * 256), Y: raster.Fix32(190 * 256)}) for j := 0; j < len(poly); j = j + 2 { rasterizer.Add1(raster.Point{ X: raster.Fix32(poly[j] * 256), Y: raster.Fix32(poly[j+1] * 256)}) } painter := raster.NewRGBAPainter(img) painter.SetColor(color) rasterizer.Rasterize(painter) err := draw2dimg.SaveToPngFile("output/TestFreetypeRasterizerNonZeroWinding.png", img) if err != nil { fmt.Println(err) } }
func BenchmarkFreetypeNonZeroWinding(b *testing.B) { var p Path p.LineTo(10, 190) draw2dbase.TraceCubic(&p, []float64{10, 190, 10, 10, 190, 10, 190, 190}, 0.5) poly := Polygon(p.points) color := color.RGBA{0, 0, 0, 0xff} for i := 0; i < b.N; i++ { img := image.NewRGBA(image.Rect(0, 0, 200, 200)) rasterizer := raster.NewRasterizer(200, 200) rasterizer.UseNonZeroWinding = true rasterizer.Start(raster.Point{ X: raster.Fix32(10 * 256), Y: raster.Fix32(190 * 256)}) for j := 0; j < len(poly); j = j + 2 { rasterizer.Add1(raster.Point{ X: raster.Fix32(poly[j] * 256), Y: raster.Fix32(poly[j+1] * 256)}) } painter := raster.NewRGBAPainter(img) painter.SetColor(color) rasterizer.Rasterize(painter) } }
// Create a new Graphic context from an image and a Painter (see Freetype-go) func NewGraphicContextWithPainter(img draw.Image, painter Painter) *ImageGraphicContext { width, height := img.Bounds().Dx(), img.Bounds().Dy() dpi := 92 ftContext := freetype.NewContext() ftContext.SetDPI(float64(dpi)) ftContext.SetClip(img.Bounds()) ftContext.SetDst(img) gc := &ImageGraphicContext{ NewStackGraphicContext(), img, painter, raster.NewRasterizer(width, height), raster.NewRasterizer(width, height), ftContext, dpi, } return gc }
// NewContext creates a new Context. func NewContext() *Context { return &Context{ r: raster.NewRasterizer(0, 0), glyphBuf: truetype.NewGlyphBuf(), fontSize: 12, dpi: 72, scale: 12 << 6, } }
func main() { // Draw a rounded corner that is one pixel wide. r := raster.NewRasterizer(50, 50) r.Start(p(5, 5)) r.Add1(p(5, 25)) r.Add2(p(5, 45), p(25, 45)) r.Add1(p(45, 45)) r.Add1(p(45, 44)) r.Add1(p(26, 44)) r.Add2(p(6, 44), p(6, 24)) r.Add1(p(6, 5)) r.Add1(p(5, 5)) // Rasterize that curve multiple times at different gammas. const ( w = 600 h = 200 ) rgba := image.NewRGBA(image.Rect(0, 0, w, h)) draw.Draw(rgba, image.Rect(0, 0, w, h/2), image.Black, image.ZP, draw.Src) draw.Draw(rgba, image.Rect(0, h/2, w, h), image.White, image.ZP, draw.Src) mask := image.NewAlpha(image.Rect(0, 0, 50, 50)) painter := raster.NewAlphaSrcPainter(mask) gammas := []float64{1.0 / 10.0, 1.0 / 3.0, 1.0 / 2.0, 2.0 / 3.0, 4.0 / 5.0, 1.0, 5.0 / 4.0, 3.0 / 2.0, 2.0, 3.0, 10.0} for i, g := range gammas { draw.Draw(mask, mask.Bounds(), image.Transparent, image.ZP, draw.Src) r.Rasterize(raster.NewGammaCorrectionPainter(painter, g)) x, y := 50*i+25, 25 draw.DrawMask(rgba, image.Rect(x, y, x+50, y+50), image.White, image.ZP, mask, image.ZP, draw.Over) y += 100 draw.DrawMask(rgba, image.Rect(x, y, x+50, y+50), image.Black, image.ZP, mask, image.ZP, draw.Over) } // Save that RGBA image to disk. f, err := os.Create("out.png") if err != nil { log.Println(err) os.Exit(1) } defer f.Close() b := bufio.NewWriter(f) err = png.Encode(b, rgba) if err != nil { log.Println(err) os.Exit(1) } err = b.Flush() if err != nil { log.Println(err) os.Exit(1) } fmt.Println("Wrote out.png OK.") }
// Make a new canvas of size w x h. func NewCanvas(w, h int) *Canvas { c := new(Canvas) c.RGBA = image.NewRGBA(image.Rect(0, 0, w, h)) c.Clear(color.White) c.painter = raster.NewRGBAPainter(c.RGBA) c.rasterizer = raster.NewRasterizer(w, h) c.rasterizer.UseNonZeroWinding = true c.SetColor(color.Black) c.path = make(raster.Path, 0, 100) c.resetPath() c.SetStroke(1, Round) return c }
func createGlyphPage(resolution resolution, glyphMaxSizePixels math.Size) *glyphPage { // Handle exceptionally large glyphs. size := math.Size{W: glyphPageWidth, H: glyphPageHeight}.Max(glyphMaxSizePixels) size.W = align(size.W, glyphSizeAlignment) size.H = align(size.H, glyphSizeAlignment) return &glyphPage{ resolution: resolution, glyphMaxSizePixels: glyphMaxSizePixels, size: size, image: image.NewAlpha(image.Rect(0, 0, size.W, size.H)), offsets: make(map[rune]math.Point), rowHeight: 0, rast: raster.NewRasterizer(glyphMaxSizePixels.W, glyphMaxSizePixels.H), } }
func main() { // Rasterize the contours to a mask image. const ( w = 400 h = 400 ) r := raster.NewRasterizer(w, h) contour(r, outside) contour(r, inside) mask := image.NewAlpha(image.Rect(0, 0, w, h)) p := raster.NewAlphaSrcPainter(mask) r.Rasterize(p) // Draw the mask image (in gray) onto an RGBA image. rgba := image.NewRGBA(image.Rect(0, 0, w, h)) gray := image.NewUniform(color.Alpha{0x1f}) draw.Draw(rgba, rgba.Bounds(), image.Black, image.ZP, draw.Src) draw.DrawMask(rgba, rgba.Bounds(), gray, image.ZP, mask, image.ZP, draw.Over) showNodes(rgba, outside) showNodes(rgba, inside) // Save that RGBA image to disk. f, err := os.Create("out.png") if err != nil { log.Println(err) os.Exit(1) } defer f.Close() b := bufio.NewWriter(f) err = png.Encode(b, rgba) if err != nil { log.Println(err) os.Exit(1) } err = b.Flush() if err != nil { log.Println(err) os.Exit(1) } fmt.Println("Wrote out.png OK.") }
// moustache draws a moustache of the specified size and droop // onto the image m and returns the result. It may overwrite the // original. func moustache(m image.Image, x, y, size, droopFactor int) image.Image { mrgba := rgba(m) p := raster.NewRGBAPainter(mrgba) p.SetColor(color.RGBA{0, 0, 0, 255}) w, h := m.Bounds().Dx(), m.Bounds().Dy() r := raster.NewRasterizer(w, h) var ( mag = raster.Fix32((10 + size) << 8) width = pt(20, 0).Mul(mag) mid = pt(x, y) droop = pt(0, droopFactor).Mul(mag) left = mid.Sub(width).Add(droop) right = mid.Add(width).Add(droop) bow = pt(0, 5).Mul(mag).Sub(droop) curlx = pt(10, 0).Mul(mag) curly = pt(0, 2).Mul(mag) risex = pt(2, 0).Mul(mag) risey = pt(0, 5).Mul(mag) ) r.Start(left) r.Add3( mid.Sub(curlx).Add(curly), mid.Sub(risex).Sub(risey), mid, ) r.Add3( mid.Add(risex).Sub(risey), mid.Add(curlx).Add(curly), right, ) r.Add2( mid.Add(bow), left, ) r.Rasterize(p) return mrgba }
func TestFreetype(t *testing.T) { var p Path p.LineTo(10, 190) c := curve.CubicCurveFloat64{10, 190, 10, 10, 190, 10, 190, 190} c.Segment(&p, flattening_threshold) poly := Polygon(p.points) rgba := color.RGBA{0, 0, 0, 0xff} bounds := image.Rect(0, 0, 200, 200) mask := image.NewAlpha(bounds) img := image.NewRGBA(bounds) rasterizer := raster.NewRasterizer(200, 200) rasterizer.UseNonZeroWinding = false rasterizer.Start(raster.Point{raster.Fix32(10 * 256), raster.Fix32(190 * 256)}) for j := 0; j < len(poly); j = j + 2 { rasterizer.Add1(raster.Point{raster.Fix32(poly[j] * 256), raster.Fix32(poly[j+1] * 256)}) } painter := raster.NewAlphaSrcPainter(mask) rasterizer.Rasterize(painter) DrawSolidRGBA(img, mask, rgba) savepng("_testFreetype.png", img) }
func main() { const ( n = 17 r = 256 * 80 ) s := raster.Fix32(r * math.Sqrt(2) / 2) t := raster.Fix32(r * math.Tan(math.Pi/8)) m := image.NewRGBA(image.Rect(0, 0, 800, 600)) draw.Draw(m, m.Bounds(), image.NewUniform(color.RGBA{63, 63, 63, 255}), image.ZP, draw.Src) mp := raster.NewRGBAPainter(m) mp.SetColor(image.Black) z := raster.NewRasterizer(800, 600) for i := 0; i < n; i++ { cx := raster.Fix32(25600 + 51200*(i%4)) cy := raster.Fix32(2560 + 32000*(i/4)) c := raster.Point{X: cx, Y: cy} theta := math.Pi * (0.5 + 0.5*float64(i)/(n-1)) dx := raster.Fix32(r * math.Cos(theta)) dy := raster.Fix32(r * math.Sin(theta)) d := raster.Point{X: dx, Y: dy} // Draw a quarter-circle approximated by two quadratic segments, // with each segment spanning 45 degrees. z.Start(c) z.Add1(c.Add(raster.Point{X: r, Y: 0})) z.Add2(c.Add(raster.Point{X: r, Y: t}), c.Add(raster.Point{X: s, Y: s})) z.Add2(c.Add(raster.Point{X: t, Y: r}), c.Add(raster.Point{X: 0, Y: r})) // Add another quadratic segment whose angle ranges between 0 and 90 degrees. // For an explanation of the magic constants 22, 150, 181 and 256, read the // comments in the freetype/raster package. dot := 256 * d.Dot(raster.Point{X: 0, Y: r}) / (r * r) multiple := raster.Fix32(150 - 22*(dot-181)/(256-181)) z.Add2(c.Add(raster.Point{X: dx, Y: r + dy}.Mul(multiple)), c.Add(d)) // Close the curve. z.Add1(c) } z.Rasterize(mp) for i := 0; i < n; i++ { cx := raster.Fix32(25600 + 51200*(i%4)) cy := raster.Fix32(2560 + 32000*(i/4)) for j := 0; j < n; j++ { theta := math.Pi * float64(j) / (n - 1) dx := raster.Fix32(r * math.Cos(theta)) dy := raster.Fix32(r * math.Sin(theta)) m.Set(int((cx+dx)/256), int((cy+dy)/256), color.RGBA{255, 255, 0, 255}) } } // Save that RGBA image to disk. f, err := os.Create("out.png") if err != nil { log.Println(err) os.Exit(1) } defer f.Close() b := bufio.NewWriter(f) err = png.Encode(b, m) if err != nil { log.Println(err) os.Exit(1) } err = b.Flush() if err != nil { log.Println(err) os.Exit(1) } fmt.Println("Wrote out.png OK.") }
// the returned zoneOfColor always has A == 256. func worldImage(t *testing.T) (im *image.RGBA, zoneOfColor map[color.RGBA]string) { scale := *flagScale width := int(scale * 360) height := int(scale * 180) im = image.NewRGBA(image.Rect(0, 0, width, height)) zoneOfColor = map[color.RGBA]string{} tab := crc32.MakeTable(crc32.IEEE + 1) drawPoly := func(col color.RGBA, xys ...int) { painter := raster.NewRGBAPainter(im) painter.SetColor(col) r := raster.NewRasterizer(width, height) r.Start(raster.Point{X: raster.Fix32(xys[0]) << 8, Y: raster.Fix32(xys[1]) << 8}) for i := 2; i < len(xys); i += 2 { r.Add1(raster.Point{X: raster.Fix32(xys[i]) << 8, Y: raster.Fix32(xys[i+1]) << 8}) } r.Add1(raster.Point{X: raster.Fix32(xys[0]) << 8, Y: raster.Fix32(xys[1]) << 8}) r.Rasterize(raster.NewMonochromePainter(painter)) } sr, err := shp.Open("world/tz_world.shp") if err != nil { t.Fatalf("Error opening world/tz_world.shp: %v; unzip it from http://efele.net/maps/tz/world/tz_world.zip", err) } defer sr.Close() for sr.Next() { i, s := sr.Shape() p, ok := s.(*shp.Polygon) if !ok { t.Fatalf("Unknown shape %T", p) } zoneName := sr.ReadAttribute(i, 0) if zoneName == "uninhabited" { continue } if _, err := time.LoadLocation(zoneName); err != nil { t.Fatalf("Failed to load: %v (%v)", zoneName, err) } hash := crc32.Checksum([]byte(zoneName), tab) col := color.RGBA{uint8(hash >> 24), uint8(hash >> 16), uint8(hash >> 8), 255} if name, ok := zoneOfColor[col]; ok { if name != zoneName { log.Fatalf("Color %+v dup: %s and %s", col, name, zoneName) } } else { zoneOfColor[col] = zoneName } var xys []int for _, pt := range p.Points { xys = append(xys, int((pt.X+180)*scale), int((90-pt.Y)*scale)) } drawPoly(col, xys...) } // adjust point from scale 32 to whatever the user is using. ap := func(x int) int { return x * int(scale) / 32 } // Fix some rendering glitches: // {186 205 234 255} = Europe/Rome drawPoly(color.RGBA{186, 205, 234, 255}, ap(6156), ap(1468), ap(6293), ap(1596), ap(6293), ap(1598), ap(6156), ap(1540)) // {136 136 180 255} = America/Boise drawPoly(color.RGBA{136, 136, 180, 255}, ap(2145), ap(1468), ap(2189), ap(1468), ap(2189), ap(1536), ap(2145), ap(1536)) // {120 247 14 255} = America/Denver drawPoly(color.RGBA{120, 247, 14, 255}, ap(2167), ap(1536), ap(2171), ap(1536), ap(2217), ap(1714), ap(2204), ap(1724), ap(2160), ap(1537)) return }
func genGlyphs(font *truetype.Font, size int, text string) (glyphs []*glyph) { scale := int32(float64(size) * dpi * (64.0 / 72.0)) clip := image.Rect(0, 0, width, height) // Calculate the rasterizer's bounds to handle the largest glyph. b := font.Bounds(scale) xmin := int(b.XMin) >> 6 ymin := -int(b.YMax) >> 6 xmax := int(b.XMax+63) >> 6 ymax := -int(b.YMin-63) >> 6 r := raster.NewRasterizer(xmax-xmin, ymax-ymin) buf := truetype.NewGlyphBuf() for _, variant := range []string{strings.ToUpper(text), strings.ToLower(text)} { pt := Pt(30, 10+int(pointToFix32(float64(size))>>8)) for _, char := range variant { idx := font.Index(char) buf.Load(font, scale, idx, truetype.FullHinting) // Calculate the integer-pixel bounds for the glyph. xmin := int(raster.Fix32(buf.B.XMin<<2)) >> 8 ymin := int(-raster.Fix32(buf.B.YMax<<2)) >> 8 xmax := int(raster.Fix32(buf.B.XMax<<2)+0xff) >> 8 ymax := int(-raster.Fix32(buf.B.YMin<<2)+0xff) >> 8 fx := raster.Fix32(-xmin << 8) fy := raster.Fix32(-ymin << 8) ix := int(pt.X >> 8) iy := int(pt.Y >> 8) // Rasterize the glyph's vectors. r.Clear() e0 := 0 for _, e1 := range buf.End { drawContour(r, buf.Point[e0:e1], fx, fy) e0 = e1 } mask := image.NewAlpha(image.Rect(0, 0, xmax-xmin, ymax-ymin)) r.Rasterize(raster.NewAlphaSrcPainter(mask)) pt.X += raster.Fix32(buf.AdvanceWidth << 2) offset := image.Point{xmin + ix, ymin + iy} glyphRect := mask.Bounds().Add(offset) dr := clip.Intersect(glyphRect) mp := image.Point{0, dr.Min.Y - glyphRect.Min.Y} glyphs = append(glyphs, &glyph{ mask: mask, mp: mp, dr: dr, }) } } return }
var fontFiles = []string{ "fonts/brandon-printed-one.ttf", "fonts/brandon-printed-two.ttf", "fonts/brandon-printed-double.ttf", // "fonts/brandon-printed-inline.ttf", // "fonts/brandon-printed-one-shadow.ttf", } var ( fonts = []*truetype.Font{} glyphset = [maxSize + 1][]*glyph{} mutex = sync.RWMutex{} variants = len(fontFiles) * 2 ) var r = raster.NewRasterizer(0, 0) func Render(size int, color *image.Uniform) (image.Image, error) { if size <= 0 || size > maxSize { return nil, InvalidSize } glyphs := getGlyphs(size) ctx := image.Rect(0, 0, width, height) img := image.NewRGBA(ctx) for i := 0; i < len(text); i++ { choice := (rand.Intn(variants) * len(text)) + i glyph := glyphs[choice] // if i == 0 { // draw.DrawMask(img, invertGlyph.dr, color, image.ZP, color, invertGlyph.mp, draw.Over) // draw.DrawMask(img, invertGlyph.dr, image.White, image.ZP, invertGlyph.mask, invertGlyph.mp, draw.Over) // } else {