### PathBuilder Example Implementation Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md An example implementation of the Adder interface using PathBuilder to store path operations. This demonstrates how to use Start, Add1, Add2, and Add3 methods. ```go type PathBuilder struct { operations []fixed.Int26_6 } func (pb *PathBuilder) Start(a fixed.Point26_6) { pb.operations = append(pb.operations, 0, a.X, a.Y, 0) } func (pb *PathBuilder) Add1(b fixed.Point26_6) { pb.operations = append(pb.operations, 1, b.X, b.Y, 0) } func (pb *PathBuilder) Add2(b, c fixed.Point26_6) { pb.operations = append(pb.operations, 2, c.X, c.Y, b.X, b.Y) } func (pb *PathBuilder) Add3(b, c, d fixed.Point26_6) { pb.operations = append(pb.operations, 3, d.X, d.Y, b.X, b.Y, c.X, c.Y) } ``` -------------------------------- ### Example Usage of AlphaSrcPainter Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Demonstrates how to create an AlphaSrcPainter and use it to rasterize content onto an alpha image. ```go img := image.NewAlpha(image.Rect(0, 0, 800, 600)) painter := raster.NewAlphaSrcPainter(img) r.Rasterize(painter) ``` -------------------------------- ### NewContext Example Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Creates a new Context for text rendering with default settings. This is the primary entry point for the freetype package, used when starting text rendering. ```go ctx := freetype.NewContext() ctx.SetFont(font) ctx.SetFontSize(24) ctx.SetDPI(96) ctx.SetDst(img) ctx.SetSrc(image.NewUniform(color.Black)) ctx.SetClip(img.Bounds()) ``` -------------------------------- ### Example Usage of AlphaOverPainter Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Demonstrates how to create an AlphaOverPainter and use it to rasterize content onto an alpha image. ```go img := image.NewAlpha(image.Rect(0, 0, 800, 600)) painter := raster.NewAlphaOverPainter(img) r.Rasterize(painter) ``` -------------------------------- ### Coordinate Conversion Examples Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Illustrates converting between pixel and fixed-point coordinate systems, and handling sub-pixel values. ```go // Convert pixel to fixed-point fixedX := pixelX * 64 fixedY := pixelY * 64 // Or using fixed package const ( I = fixed.Int26_6(1) << 6 // 1.0 in fixed point ) // Convert fixed-point to float64 pixelX := float64(fixedX) / 64.0 // Sub-pixel coordinates quarterPixel := fixed.Int26_6(16) // 0.25 pixels ``` -------------------------------- ### Complete Stroking Example Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-stroke.md Demonstrates how to create a rasterizer, define a path, add a stroke with round caps and joins, and rasterize it to an image. ```go package main import ( "github.com/golang/freetype/raster" "golang.org/x/image/math/fixed" "image" ) func main() { // Create rasterizer and image r := raster.NewRasterizer(400, 400) img := image.NewAlpha(image.Rect(0, 0, 400, 400)) // Define a path: letter L shape path := raster.Path{ 0, 100*64, 100*64, 0, // Start at (100, 100) 1, 100*64, 300*64, 0, // Line down to (100, 300) 1, 300*64, 300*64, 0, // Line right to (300, 300) } // Stroke with 10-pixel width, round caps and joins width := fixed.Int26_6(10 * 64) r.AddStroke(path, width, raster.RoundCapper, raster.RoundJoiner) // Rasterize painter := raster.NewAlphaSrcPainter(img) r.Rasterize(painter) // img now contains the stroked L shape } ``` -------------------------------- ### Complete Rasterizer Example Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Demonstrates creating a rasterizer, adding a rectangular path, and rasterizing it to an alpha image. Ensure correct fixed-point coordinate conversion. ```go package main import ( "github.com/golang/freetype/raster" "golang.org/x/image/math/fixed" "image" "image/draw" ) func main() { // Create rasterizer r := raster.NewRasterizer(200, 200) // Define a rectangle path rect := raster.Path{ 0, 50*64, 50*64, 0, // Start at (50, 50) 1, 150*64, 50*64, 0, // Line to (150, 50) 1, 150*64, 150*64, 0, // Line to (150, 150) 1, 50*64, 150*64, 0, // Line to (50, 150) 1, 50*64, 50*64, 0, // Close to start } r.AddPath(rect) // Rasterize to image img := image.NewAlpha(image.Rect(0, 0, 200, 200)) painter := raster.NewAlphaSrcPainter(img) r.Rasterize(painter) // img now contains the anti-aliased rectangle } ``` -------------------------------- ### Start Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Initiates a new path segment at a specified starting point. This method must be called before adding any lines or curves. ```APIDOC ## Start ### Description Starts a new curve at the given point. This must be called before adding any segments to a curve. ### Method `Start` ### Parameters #### Path Parameters - **a** (fixed.Point26_6) - Yes - Starting point in 26.6 fixed-point format ### Example ```go // Start at pixel (100, 50) with sub-pixel precision start := fixed.Point26_6{X: 100 * 64, Y: 50 * 64} r.Start(start) ``` ``` -------------------------------- ### Path Manipulation Examples Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Demonstrates common operations on raster paths, such as appending segments, clearing the path, and creating paths from a builder. ```go // Append operations path = append(path, 1, x*64, y*64, 0) // Add line // Clear path path = path[:0] // Create from builder var path raster.Path builder := PathBuilder{path} builder.Start(p1) builder.Add1(p2) builder.Add2(control, p3) ``` -------------------------------- ### Adder Interface Methods Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Details the methods of the Adder interface: Start, Add1, Add2, and Add3, explaining their purpose in path construction. ```go func (a Adder) Start(point fixed.Point26_6) ``` ```go func (a Adder) Add1(point fixed.Point26_6) ``` ```go func (a Adder) Add2(controlPoint, endpoint fixed.Point26_6) ``` ```go func (a Adder) Add3(control1, control2, endpoint fixed.Point26_6) ``` -------------------------------- ### Start New Curve Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Initiates a new curve by defining its starting point. This method must be called before adding any segments to a curve. ```go // Start at pixel (100, 50) with sub-pixel precision start := fixed.Point26_6{X: 100 * 64, Y: 50 * 64} r.Start(start) ``` -------------------------------- ### Custom Painter Implementation Example Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md An example of a custom Painter implementation that iterates through spans and paints them onto an RGBA image. Ensure the Y coordinate is within the image bounds before painting. ```go type MyPainter struct { img *image.RGBA } func (p *MyPainter) Paint(ss []raster.Span, done bool) { for _, s := range ss { if s.Y < 0 || s.Y >= p.img.Bounds().Max.Y { continue } // Paint span s.Y from s.X0 to s.X1 with alpha s.Alpha } } ``` -------------------------------- ### ParseFont Example Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Convenience wrapper to parse a TrueType font from bytes. Use `truetype.Parse()` directly if you already import `truetype`. ```go fontBytes, _ := ioutil.ReadFile("Arial.ttf") font, err := freetype.ParseFont(fontBytes) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Iterating Through Glyph Points Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-glyphbuf.md Example of how to iterate through the points of a glyph buffer and identify on-curve and off-curve points. ```go // Iterate through glyph points for i, p := range buf.Points { if p.Flags&0x01 != 0 { fmt.Printf("On-curve point at (%.2f, %.2f)\n", float64(p.X)/64, float64(p.Y)/64) } else { fmt.Printf("Off-curve control point at (%.2f, %.2f)\n", float64(p.X)/64, float64(p.Y)/64) } } ``` -------------------------------- ### Path Encoding: Start Opcode Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Encodes the start of a new curve at a given (X, Y) point. The 4th element is unused padding. ```go [0, X, Y, _] ``` -------------------------------- ### Load Font, Create Face, Get Metrics, Measure Text, Render Glyph Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Demonstrates loading a TrueType font, creating a font face with custom options, retrieving font metrics, measuring text width, and rendering a specific glyph. Ensure 'Arial.ttf' is available in the same directory. ```go package main import ( "fmt" "github.com/golang/freetype/truetype" "golang.org/x/image/font" "golang.org/x/image/math/fixed" "io/ioutil" ) func main() { // Load font fontData, _ := ioutil.ReadFile("Arial.ttf") ttf, _ := truetype.Parse(fontData) // Create face with options opts := &truetype.Options{ Size: 24, DPI: 72, Hinting: font.HintingFull, } face := truetype.NewFace(ttf, opts) // Get metrics metrics := face.Metrics() fmt.Printf("Ascent: %d, Descent: %d, Height: %d\n", metrics.Ascent, metrics.Descent, metrics.Height) // Measure text width width := fixed.Int26_6(0) for _, r := range "Hello" { _, advance, _ := face.GlyphBounds(r) width += advance } fmt.Printf("Text width: %.2f pixels\n", float64(width)/64) // Render glyph dot := fixed.Point26_6{X: 0, Y: 0} dr, mask, maskp, _, ok := face.Glyph(dot, 'A') if ok { fmt.Printf("Glyph 'A': %v (mask at %v)\n", dr, maskp) } } ``` -------------------------------- ### Pt Example Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Converts integer pixel coordinates to 26.6 fixed-point format. Use this when you have integer pixel coordinates and need to convert them to fixed-point for Context.DrawString(). ```go // Pixel (100, 200) in fixed-point pt := freetype.Pt(100, 200) // Sub-pixel positioning would require manual fixed-point arithmetic subpixel := fixed.Point26_6{X: 100*64 + 32, Y: 200*64} // +0.5 in Y ``` -------------------------------- ### Drawing Colored Shapes with RGBAPainter Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Example of drawing multiple colored paths onto an RGBA image using RGBAPainter. Ensure necessary packages are imported. ```go import ( "image" "image/color" "image/draw" "github.com/golang/freetype/raster" "golang.org/x/image/math/fixed" ) func drawColoredShape(img *image.RGBA, paths []raster.Path) { r := raster.NewRasterizer(img.Bounds().Dx(), img.Bounds().Dy()) painter := &raster.RGBAPainter{ Image: img, Op: draw.Over, } for _, path := range paths { // Set color to blue painter.cr = 0x0000 painter.cg = 0x0000 painter.cb = 0xffff painter.ca = 0xffff r.Clear() r.AddPath(path) r.Rasterize(painter) } } ``` -------------------------------- ### Vector Rotation Example Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Demonstrates a clockwise 90-degree rotation of a 2D vector using fixed-point arithmetic. This pattern is used internally for rotation utilities. ```go // Rotate a vector 90 degrees clockwise rotated := fixed.Point26_6{-vector.Y, vector.X} ``` -------------------------------- ### Text Measurement using truetype.Face Source: https://github.com/golang/freetype/blob/master/_autodocs/README.md This example shows how to measure the width of a string using the truetype package's Face interface. It iterates over runes, calculates advance width, and converts it to pixel units. ```go face := truetype.NewFace(font, &truetype.Options{Size: 24}) width := fixed.Int26_6(0) for _, r := range "Hello" { _, advance, _ := face.GlyphBounds(r) width += advance } pixelWidth := float64(width) / 64.0 ``` -------------------------------- ### Differentiate Format vs. Unsupported Errors in Go Source: https://github.com/golang/freetype/blob/master/_autodocs/errors.md This example demonstrates how to differentiate between fatal font format errors and recoverable `UnsupportedError` exceptions during font parsing. This allows for more granular error handling. ```go font, err := truetype.Parse(fontData) if err != nil { if _, ok := err.(truetype.UnsupportedError); ok { // May still be usable if specific features aren't needed log.Println("Warning: unsupported font features") } else { // Fatal format error log.Fatal(err) } } ``` -------------------------------- ### NewContext Function Signature Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Creates a new Context for text rendering with default settings. This is the primary entry point for the freetype package, used when starting text rendering. ```go func NewContext() *Context ``` -------------------------------- ### Get Glyph Bounds and Advance Width Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Obtains the bounding box and advance width for a glyph without rendering it. Useful for layout calculations. ```go bounds, advance, ok := face.GlyphBounds('A') if ok { height := bounds.Max.Y - bounds.Min.Y } ``` -------------------------------- ### Get Font Metrics Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Retrieves the overall font metrics, including ascent, descent, and height. Provides global font spacing information. ```go metrics := face.Metrics() height := metrics.Height ``` -------------------------------- ### Painter Example with Spans Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Iterates through a slice of Spans, skipping sentinel spans, converting alpha, and painting pixels within the span's boundaries. This demonstrates a typical usage pattern for raster spans. ```go func (p *MyPainter) Paint(ss []raster.Span, done bool) { for _, s := range ss { if s.Alpha == 0 { // Skip sentinel span continue } // Convert alpha from 16-bit to 8-bit alpha := uint8(s.Alpha >> 8) // Paint from s.X0 to s.X1-1 at row s.Y for x := s.X0; x < s.X1; x++ { // p.paintPixel(x, s.Y, alpha) } } } ``` -------------------------------- ### Adder Interface Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md The Adder interface defines methods for accumulating points on a path, used by the Rasterizer. It includes methods to start a new curve, add lines, quadratic Bézier curves, and cubic Bézier curves. ```APIDOC ## Interface: Adder ### Description An interface for accumulating points on a path. The Rasterizer implements this interface. ### Methods #### Start ```go func (a Adder) Start(point fixed.Point26_6) ``` Starts a new curve at the given point. #### Add1 ```go func (a Adder) Add1(point fixed.Point26_6) ``` Adds a line from the current point to the given point. #### Add2 ```go func (a Adder) Add2(controlPoint, endpoint fixed.Point26_6) ``` Adds a quadratic Bézier curve. Current point → controlPoint → endpoint. #### Add3 ```go func (a Adder) Add3(control1, control2, endpoint fixed.Point26_6) ``` Adds a cubic Bézier curve. Current point → control1 → control2 → endpoint. ``` -------------------------------- ### Constructing a Path Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Demonstrates how to construct a `raster.Path` using opcodes and fixed-point coordinates. ```go path := raster.Path{ // Start at (100, 100) 0, 100*64, 100*64, 0, // Line to (200, 100) 1, 200*64, 100*64, 0, // Quadratic curve to (250, 150) via control (225, 75) 2, 250*64, 150*64, 225*64, 75*64, // Line to (200, 200) 1, 200*64, 200*64, 0, // Cubic curve back to start via (150,225) (100,225) 3, 100*64, 100*64, 150*64, 225*64, 100*64, 225*64, } ``` -------------------------------- ### Using Stroke and Cap/Join Factories Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Demonstrates how to add a stroke to a path using predefined cap and join styles. Ensure the path, width, capper, and joiner are properly defined. ```go width := fixed.Int26_6(4 * 64) r.AddStroke(path, width, raster.RoundCapper, raster.RoundJoiner) ``` -------------------------------- ### Sentinel Span Example Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Represents the end of rasterization data. This span has all zero fields and is typically skipped by painters. ```go Span{Y: 0, X0: 0, X1: 0, Alpha: 0} ``` -------------------------------- ### Initialize freetype.Context Source: https://github.com/golang/freetype/blob/master/_autodocs/freetype-context.md Creates a new freetype.Context with default settings. No font, destination, or source image are set initially. ```Go ctx := freetype.NewContext() ``` -------------------------------- ### Complete Rasterization Workflow Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Demonstrates a full rasterization process: creating an image, defining a path (a circle-like shape), rasterizing it using AlphaSrcPainter, and saving the result as a PNG file. Requires image, png, os, and freetype/raster packages. ```go package main import ( "github.com/golang/freetype/raster" "golang.org/x/image/math/fixed" "image" "image/draw" "image/png" "os" ) func main() { // Create image img := image.NewAlpha(image.Rect(0, 0, 400, 300)) // Create rasterizer r := raster.NewRasterizer(400, 300) // Create path: a circle-like shape path := raster.Path{ 0, 200*64, 50*64, 0, // Start at (200, 50) 1, 350*64, 200*64, 0, // Line to (350, 200) 1, 200*64, 350*64, 0, // Line to (200, 350) 1, 50*64, 200*64, 0, // Line to (50, 200) 1, 200*64, 50*64, 0, // Close } // Rasterize with AlphaSrc painter r.AddPath(path) painter := raster.NewAlphaSrcPainter(img) r.Rasterize(painter) // Save image out, _ := os.Create("output.png") png.Encode(out, img) out.Close() } ``` -------------------------------- ### Using Paths with Rasterizer Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Shows how to use a constructed `raster.Path` with a `raster.Rasterizer` and a painter to render an image. ```go r := raster.NewRasterizer(400, 300) r.AddPath(path) painter := raster.NewAlphaSrcPainter(img) r.Rasterize(painter) ``` -------------------------------- ### Create and Use Rasterizer Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Initializes a Rasterizer for a specific canvas size and demonstrates its usage for rasterizing paths. It also shows how to resize the rasterizer and clear it for new paths. ```go func NewRasterizer(width, height int) *Rasterizer ``` ```go // Create rasterizer for 800x600 canvas r := raster.NewRasterizer(800, 600) // Create path and rasterize r.AddPath(myPath) painter := raster.NewAlphaSrcPainter(myImage) r.Rasterize(painter) // Resize for a different canvas r.SetBounds(1024, 768) r.Clear() r.AddPath(anotherPath) r.Rasterize(painter) ``` -------------------------------- ### Using PainterFunc Adapter Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Demonstrates how to use a function directly as a Painter by adapting it with raster.PainterFunc. This is useful for simple span handling logic. ```go // Use a function directly as a Painter painter := raster.PainterFunc(func(ss []raster.Span, done bool) { for _, s := range ss { // Handle span s } }) r.Rasterize(painter) ``` -------------------------------- ### Simple Text Rendering with FreeType Source: https://github.com/golang/freetype/blob/master/_autodocs/README.md This snippet demonstrates how to perform simple text rendering using the freetype package. It initializes a new context, sets font properties, and draws a string onto an image. ```go ctx := freetype.NewContext() ctx.SetFont(font) ctx.SetFontSize(24) ctx.SetDPI(72) ctx.SetDst(img) ctx.SetSrc(image.NewUniform(color.Black)) ctx.SetClip(img.Bounds()) ctx.DrawString("Hello", freetype.Pt(10, 50)) ``` -------------------------------- ### AddPath Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Adds a complete path, which may contain multiple curves, to the rasterizer. The path format encodes start and segment operations as a flat array. ```APIDOC ## AddPath ### Description Adds a complete path (which may contain multiple curves) to the rasterizer. The path format encodes start and segment operations as a flat array. ### Method func (r *Rasterizer) AddPath(p Path) ### Parameters #### Path Parameters - **p** (Path) - Required - Path array with encoded segments **Path Format:** - Opcode 0: Start — `[0, X, Y, _]` (4 elements) - Opcode 1: Add1 — `[1, X, Y, _]` (4 elements) - Opcode 2: Add2 — `[2, X, Y, CX, CY]` (6 elements) - Opcode 3: Add3 — `[3, X, Y, CX1, CY1, CX2, CY2]` (8 elements) ### Request Example ```go // Path format: [start X Y _, add1 X Y _, add1 X Y _] path := raster.Path{ 0, 100*64, 100*64, 0, // Start at (100, 100) 1, 200*64, 100*64, 0, // Line to (200, 100) 1, 200*64, 200*64, 0, // Line to (200, 200) 1, 100*64, 200*64, 0, // Line to (100, 200) 1, 100*64, 100*64, 0, // Close to start } r.AddPath(path) ``` ``` -------------------------------- ### Clear rasterizer state Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Resets the rasterizer to its initial state, discarding any previously accumulated path data. Call this before starting a new rasterization process. ```go func (r *Rasterizer) Clear() r.Clear() // Reset for a new rasterization ``` -------------------------------- ### Get Kerning Adjustment Between Glyphs Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Calculates the kerning adjustment value between two consecutive runes. This value is typically negative to bring glyphs closer. ```go kern := face.Kern('A', 'V') // Usually negative (closer together) ``` -------------------------------- ### Get Glyph Mask and Metrics Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Retrieves the alpha mask image, its offset, and advance metrics for a given rune. Use when glyph rendering is required. ```go face := truetype.NewFace(font, nil) dot := fixed.Point26_6{X: 0, Y: 0} dr, mask, maskp, advance, ok := face.Glyph(dot, 'A') if !ok { // Glyph not found } // dr: destination rectangle // mask: alpha mask image // maskp: offset of mask relative to dr // advance: width to advance cursor ``` -------------------------------- ### Get Kerning Adjustment Between Glyphs Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Calculates the horizontal kerning adjustment needed between two consecutive glyphs. A positive value indicates increased spacing. ```go // Kern between 'A' and 'V' idxA := font.Index('A') idxV := font.Index('V') kern := font.Kern(scale, idxA, idxV) // Typically negative: these glyphs should be closer together ``` -------------------------------- ### Get Scaled Glyph Bounds Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Calculates the union of all glyph bounding boxes, scaled by the provided factor. Useful for determining the overall dimensions of text. ```go // Get bounds for 12-point font at 72 DPI scale := fixed.Int26_6(12 * 72 * 64 / 72) // = 12 * 64 bounds := font.Bounds(scale) height := bounds.Max.Y - bounds.Min.Y ``` -------------------------------- ### Create truetype Face with Default Options Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Creates a new font.Face using default rendering options. This is suitable for standard text rendering at 12pt with 72 DPI and no hinting. ```Go import ( "github.com/golang/freetype/truetype" "golang.org/x/image/font" "io/ioutil" ) fontData, _ := ioutil.ReadFile("myfont.ttf") ttf, _ := truetype.Parse(fontData) // Default options (12pt, 72 DPI, no hinting) face := truetype.NewFace(ttf, nil) ``` -------------------------------- ### Get Glyph Index for Rune Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Obtains the glyph index corresponding to a given Unicode rune. Returns 0 if the rune is not present in the font's character map. ```go idx := font.Index('A') // Get index for uppercase A if idx == 0 { // Character not in font } ``` -------------------------------- ### Shape Rendering with rasterizer Source: https://github.com/golang/freetype/blob/master/_autodocs/README.md This snippet illustrates how to render shapes using the raster package. It initializes a rasterizer, adds a stroked path with specified caps and joiners, and then rasterizes it onto a painter. ```go r := raster.NewRasterizer(width, height) path := raster.Path{ /* your path data */ } r.AddStroke(path, strokeWidth, raster.RoundCapper, raster.RoundJoiner) painter := raster.NewAlphaSrcPainter(img) r.Rasterize(painter) ``` -------------------------------- ### Create Font Face for Go Image/Font Integration Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Creates a font.Face for standard Go image/font integration. Use when you need text measurement or the standard font.Face interface. Defaults are applied when options are nil or zero-valued. ```go func NewFace(f *Font, opts *Options) font.Face ``` ```go // Minimal setup face := truetype.NewFace(font, nil) // With configuration face := truetype.NewFace(font, &truetype.Options{ Size: 24, DPI: 96, Hinting: font.HintingFull, GlyphCacheEntries: 1024, SubPixelsX: 8, SubPixelsY: 2, }) ``` -------------------------------- ### Get Font Units Per Em Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Retrieves the number of font design units (FUnits) within the font's em-square. This value is crucial for scaling font metrics. ```go emUnits := font.FUnitsPerEm() // If 2048, then 1 em = 2048 FUnits ``` -------------------------------- ### Get Vertical Glyph Metrics Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Retrieves the vertical metrics for a glyph, including its advance height and top side bearing, scaled to the specified factor. Use this for vertical text layout. ```go type VMetric struct { AdvanceHeight fixed.Int26_6 TopSideBearing fixed.Int26_6 } ``` -------------------------------- ### Configure truetype Options for Full Hinting Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Enables full hinting for glyph rendering, which can improve rendering quality at small sizes. This is an option from the golang.org/x/image/font package. ```Go // Enable full hinting opts := &truetype.Options{Hinting: font.HintingFull} ``` -------------------------------- ### Get Horizontal Glyph Metrics Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Retrieves the horizontal metrics for a glyph, including its advance width and left side bearing, scaled to the specified factor. Use this to position glyphs horizontally. ```go metric := font.HMetric(scale, idx) width := metric.AdvanceWidth // In fixed-point units bearing := metric.LeftSideBearing ``` -------------------------------- ### SetHinting Source: https://github.com/golang/freetype/blob/master/_autodocs/freetype-context.md Configures the hinting policy for glyph rendering, influencing how glyph outlines are quantized. Valid options include `HintingNone`, `HintingVertical`, and `HintingFull` from the `golang.org/x/image/font` package. ```APIDOC ## SetHinting ### Description Sets the hinting policy for glyph rendering. Valid values from `golang.org/x/image/font` are `HintingNone`, `HintingVertical`, or `HintingFull`. Hinting affects how glyph outlines are quantized but not their bounding boxes or advance widths. ### Method - Context.SetHinting ### Parameters #### Path Parameters - **hinting** (font.Hinting) - Required - Hinting policy from golang.org/x/image/font ### Example ```go import "golang.org/x/image/font" ctx.SetHinting(font.HintingFull) // Best quality with hinting ctx.SetHinting(font.HintingNone) // No hinting ``` ``` -------------------------------- ### Reusing GlyphBuf for Multiple Glyphs Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-glyphbuf.md Demonstrates how to reuse a GlyphBuf instance to load and process multiple glyphs efficiently. Ensure error handling for each load operation. ```go buf := &truetype.GlyphBuf{} // Load multiple glyphs for _, rune := range "Hello" { idx := font.Index(rune) err := buf.Load(font, scale, idx, font.HintingNone) if err != nil { // Handle error continue } // Use buf.Points, buf.Bounds, buf.AdvanceWidth... processGlyph(buf) } ``` -------------------------------- ### AddPath with encoded segments Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Adds a complete path to the rasterizer. The path is encoded as a flat array of operations (start, add1, add2, add3) with their respective coordinates. Use this to define complex shapes. ```go func (r *Rasterizer) AddPath(p Path) // Path format: [start X Y _, add1 X Y _, add1 X Y _] path := raster.Path{ 0, 100*64, 100*64, 0, // Start at (100, 100) 1, 200*64, 100*64, 0, // Line to (200, 100) 1, 200*64, 200*64, 0, // Line to (200, 200) 1, 100*64, 200*64, 0, // Line to (100, 200) 1, 100*64, 100*64, 0, // Close to start } r.AddPath(path) ``` -------------------------------- ### Define font.Hinting Constants Source: https://github.com/golang/freetype/blob/master/_autodocs/types.md Defines hinting policy constants for font rendering, including no hinting, vertical hinting, and full hinting. ```go const ( HintingNone font.Hinting = 0 HintingVertical = 1 HintingFull = 2 ) ``` -------------------------------- ### Get Font Name by Identifier Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-font.md Fetches a specific name string from the font's name table using a predefined identifier. Returns an empty string if the name is not found or an error occurs. ```go familyName := font.Name(truetype.NameIDFontFamily) fullName := font.Name(truetype.NameIDFontFullName) ``` -------------------------------- ### Implement Custom Painter for Rasterization Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Create a custom painter by implementing the raster.Painter interface. This allows for custom pixel processing during rasterization, such as handling transparency or specific color mapping. ```go type MyPainter struct { img *image.RGBA } func (p *MyPainter) Paint(ss []raster.Span, done bool) { for _, s := range ss { if s.Alpha == 0 { continue // Skip transparent spans } alpha := uint8(s.Alpha >> 8) // Convert to 8-bit for x := s.X0; x < s.X1; x++ { // Paint pixel (x, s.Y) with alpha } } } // Use custom painter r := raster.NewRasterizer(width, height) r.AddPath(path) r.Rasterize(&MyPainter{img}) ``` -------------------------------- ### Create truetype Face with Custom Options Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-face.md Creates a new font.Face with custom rendering options, including size, DPI, and hinting. Use this for specific display resolutions or rendering requirements. ```Go import ( "github.com/golang/freetype/truetype" "golang.org/x/image/font" "io/ioutil" ) fontData, _ := ioutil.ReadFile("myfont.ttf") ttf, _ := truetype.Parse(fontData) // With custom options face := truetype.NewFace(ttf, &truetype.Options{ Size: 24, DPI: 72, Hinting: font.HintingFull, }) ``` -------------------------------- ### Representing Sub-Pixel in Fixed-Point Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Demonstrates how to represent a sub-pixel value, such as 0.5 pixels, using the 26.6 fixed-point format. ```go halfPixel := fixed.Int26_6(32) ``` -------------------------------- ### Use font.Face Interface for Text Metrics and Glyphs Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Obtain a font.Face from a TrueType font for advanced text manipulation. Use it to get font metrics, measure text width, and retrieve individual glyph information including bounds and advance. ```go import "golang.org/x/image/font" font, _ := truetype.Parse(fontBytes) opts := &truetype.Options{ Size: 24, DPI: 72, Hinting: font.HintingFull, } face := truetype.NewFace(font, opts) defer face.Close() // Get font metrics metrics := face.Metrics() ascent := metrics.Ascent // Measure text width := fixed.Int26_6(0) for _, r := range "Hello" { _, advance, _ := face.GlyphBounds(r) width += advance } // Get individual glyphs dot := fixed.Point26_6{X: 0, Y: 0} dr, mask, maskp, advance, ok := face.Glyph(dot, 'A') ``` -------------------------------- ### Load Glyph Outlines for Rendering Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Parse a TrueType font and use a GlyphBuf to load outlines for characters. Iterate through the loaded contour points to process or render the glyph shapes. Ensure correct scaling and hinting are applied. ```go font, _ := truetype.Parse(fontBytes) buf := &truetype.GlyphBuf{} scale := fixed.Int26_6(24 * 72 * 64 / 72) // 24pt, 72 DPI for _, r := range "Hello" { idx := font.Index(r) buf.Load(font, scale, idx, font.HintingNone) // Access glyph data for i := 0; i < len(buf.Ends); i++ { var start int if i > 0 { start = buf.Ends[i-1] } end := buf.Ends[i] contourPoints := buf.Points[start:end] // Process contour... } } ``` -------------------------------- ### Options Source: https://github.com/golang/freetype/blob/master/_autodocs/types.md Configuration options for creating a new font face. These settings control font size, hinting, and caching behavior. ```APIDOC ## Options ### Description Configuration options for creating a new font face. These settings control font size, hinting, and caching behavior. ### Type Definition ```go type Options struct { Size float64 DPI float64 Hinting font.Hinting GlyphCacheEntries int SubPixelsX int SubPixelsY int } ``` ### Fields - **Size** (float64) - Default: 12 - Font size in points - **DPI** (float64) - Default: 72 - Dots per inch - **Hinting** (font.Hinting) - Default: HintingNone - Hinting policy - **GlyphCacheEntries** (int) - Default: 512 - Cache entries (must be power of 2) - **SubPixelsX** (int) - Default: 4 - Sub-pixel precision X (must be power of 2) - **SubPixelsY** (int) - Default: 1 - Sub-pixel precision Y (must be power of 2) ``` -------------------------------- ### File Sizes (Human Readable) Source: https://github.com/golang/freetype/blob/master/_autodocs/INDEX.md Displays the human-readable file sizes of various documentation files within the project. Useful for understanding the scope and organization of the documentation. ```text 136K total 13K overview.md 12K functions-reference.md 12K README.md 11K types.md 9.3K raster-rasterizer.md 8.1K truetype-font.md 8.0K raster-painter.md 7.9K freetype-context.md 7.8K raster-types.md 7.6K errors.md 7.0K raster-stroke.md 7.0K truetype-face.md 5.9K truetype-glyphbuf.md ``` -------------------------------- ### Create New Rasterizer Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-rasterizer.md Creates a new Rasterizer instance with specified width and height. Initializes internal buffers for area accumulation. ```go raster := raster.NewRasterizer(800, 600) ``` -------------------------------- ### JoinerFunc Adapter Implementation Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-stroke.md Adapts a function to the Joiner interface by implementing the Join method. ```go type JoinerFunc func(Adder, Adder, fixed.Int26_6, fixed.Point26_6, fixed.Point26_6, fixed.Point26_6) func (f JoinerFunc) Join(lhs, rhs Adder, halfWidth fixed.Int26_6, pivot, n0, n1 fixed.Point26_6) { f(lhs, rhs, halfWidth, pivot, n0, n1) } ``` -------------------------------- ### High-Level Flow Diagram Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Illustrates the data flow from TTF file bytes to rendered image output using the Freetype-Go packages. ```text TTF File Bytes ↓ truetype.Parse() ↓ truetype.Font (parsed font metadata) ↓ truetype.NewFace() or Context.SetFont() ↓ freetype.Context (text rendering) or raster.Rasterizer (vector rasterization) ↓ Image (output with rendered glyphs) ``` -------------------------------- ### Create Alpha Source Painter Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Constructs a painter that composites spans onto an *image.Alpha using the Src operator, suitable for rendering glyphs to an alpha mask. ```go func NewAlphaSrcPainter(m *image.Alpha) AlphaSrcPainter ``` ```go img := image.NewAlpha(image.Rect(0, 0, 400, 300)) painter := raster.NewAlphaSrcPainter(img) r := raster.NewRasterizer(400, 300) r.AddPath(path) r.Rasterize(painter) // img now contains the rasterized path ``` -------------------------------- ### Draw Text Strings with FreeType Context Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Load a font, create an image, and use the FreeType context to draw text strings onto the image. Ensure the font file is accessible and configure context properties like font, size, DPI, source, destination, and clipping area. ```go // Load font fontBytes, _ := ioutil.ReadFile("font.ttf") font, _ := freetype.ParseFont(fontBytes) // Create image img := image.NewRGBA(image.Rect(0, 0, 800, 600)) // Create context and configure ctx := freetype.NewContext() ctx.SetFont(font) ctx.SetFontSize(24) ctx.SetDPI(72) ctx.SetSrc(image.NewUniform(color.Black)) ctx.SetDst(img) ctx.SetClip(img.Bounds()) // Draw text pos := freetype.Pt(10, 50) ctx.DrawString("Hello, World!", pos) ``` -------------------------------- ### Path String Representation Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-types.md Provides a human-readable string representation of a path, useful for debugging. ```go func (p Path) String() string ``` ```go fmt.Println(path.String()) // Output: S0[100 100] A1[200 100] A1[200 200] ... ``` -------------------------------- ### Create Alpha Over Painter Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Creates a painter that composites spans onto an *image.Alpha using the Over operator, ideal for blending multiple shapes or soft shadows. ```go func NewAlphaOverPainter(m *image.Alpha) AlphaOverPainter ``` ```go img := image.NewAlpha(image.Rect(0, 0, 400, 300)) painter := raster.NewAlphaOverPainter(img) // Draw first path r.AddPath(path1) r.Rasterize(painter) // Add second path (composites over first) r.Clear() r.AddPath(path2) r.Rasterize(painter) ``` -------------------------------- ### Setting RGBAPainter Color Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Demonstrates how to set the color for the RGBAPainter before rasterizing. Color values are 16-bit. ```go painter := &raster.RGBAPainter{ Image: img, Op: draw.Over, } // Set to opaque red painter.cr = 0xffff painter.cg = 0x0000 painter.cb = 0x0000 painter.ca = 0xffff r.Rasterize(painter) ``` -------------------------------- ### Direct Vector Rasterization with Rasterizer Source: https://github.com/golang/freetype/blob/master/_autodocs/overview.md Create a rasterizer and define a path using vector coordinates. Add the path to the rasterizer and then rasterize it onto an image. This pattern is useful for drawing shapes directly from vector data. ```go // Create rasterizer r := raster.NewRasterizer(400, 300) // Define path (rectangle) path := raster.Path{ 0, 50*64, 50*64, 0, // Start at (50, 50) 1, 350*64, 50*64, 0, // Line to (350, 50) 1, 350*64, 250*64, 0, // Line to (350, 250) 1, 50*64, 250*64, 0, // Line to (50, 250) 1, 50*64, 50*64, 0, // Close to start } // Rasterize img := image.NewAlpha(image.Rect(0, 0, 400, 300)) r.AddPath(path) r.Rasterize(raster.NewAlphaSrcPainter(img)) ``` -------------------------------- ### Extracting Contour Points Source: https://github.com/golang/freetype/blob/master/_autodocs/truetype-glyphbuf.md Demonstrates how to extract points belonging to each contour from the GlyphBuf's Points and Ends slices. ```go // Get the first contour's points var start int for i := 0; i < len(buf.Ends); i++ { end := buf.Ends[i] contourPoints := buf.Points[start:end] fmt.Printf("Contour %d has %d points\n", i, len(contourPoints)) start = end } ``` -------------------------------- ### NewAlphaSrcPainter Constructor Source: https://github.com/golang/freetype/blob/master/_autodocs/raster-painter.md Creates a new AlphaSrcPainter for a given alpha image. This painter uses the Src composition operator, overwriting existing pixel values. ```go func NewAlphaSrcPainter(m *image.Alpha) AlphaSrcPainter ``` -------------------------------- ### Set Hinting Policy in freetype.Context Source: https://github.com/golang/freetype/blob/master/_autodocs/freetype-context.md Specifies the hinting policy for glyph rendering, impacting outline quantization. Use `font.HintingFull` for best quality or `font.HintingNone` for no hinting. ```Go import "golang.org/x/image/font" ctx.SetHinting(font.HintingFull) // Best quality with hinting ctx.SetHinting(font.HintingNone) // No hinting ``` -------------------------------- ### NewContext Source: https://github.com/golang/freetype/blob/master/_autodocs/freetype-context.md Creates a new freetype.Context with default rendering settings. The default values include a font size of 12 points, 72 DPI, and no hinting. No font, destination, or source image is set initially. ```APIDOC ## NewContext ### Description Creates a new Context with default values: Font size: 12 points, DPI: 72, Hinting: None, No font, destination, or source image set. ### Returns - *Context - A pointer to a newly initialized Context. ``` -------------------------------- ### Predefined Cap and Join Styles Source: https://github.com/golang/freetype/blob/master/_autodocs/functions-reference.md Defines predefined cap and join styles as variables for use in stroking paths. These are constants and not functions. ```go var RoundCapper Capper = CapperFunc(roundCapper) var ButtCapper Capper = CapperFunc(buttCapper) var SquareCapper Capper = CapperFunc(squareCapper) var RoundJoiner Joiner = JoinerFunc(roundJoiner) var BevelJoiner Joiner = JoinerFunc(bevelJoiner) ```