### FontFace Constructor Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Demonstrates how to load a font face from a stream, either from a file path or an existing stream. It also shows how to access basic font properties. ```APIDOC ## FontFace — Load a font from a stream `FontFace` is the root object for a single typeface. Constructing it reads the entire font file into memory; after construction the stream may be closed. All metrics properties (`Family`, `FullName`, `Weight`, `Style`, `IsFixedWidth`, etc.) are immediately available. Pass `pixelSize` (not point size) to the metric and glyph methods. ```csharp using SharpFont; using System.IO; using System.Runtime.InteropServices; // Load directly from a file path FontFace face; using (var stream = File.OpenRead("Fonts/OpenSans-Regular.ttf")) face = new FontFace(stream); Console.WriteLine(face.Family); // "Open Sans" Console.WriteLine(face.FullName); // "Open Sans Regular" Console.WriteLine(face.Weight); // FontWeight.Normal Console.WriteLine(face.Style); // FontStyle.Regular Console.WriteLine(face.IsFixedWidth); // false ``` ``` -------------------------------- ### Load FontFace from Stream Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Demonstrates loading a font file directly from a stream using FontFace. The stream can be closed after construction. Metrics are immediately available. ```csharp using SharpFont; using System.IO; using System.Runtime.InteropServices; // Load directly from a file path FontFace face; using (var stream = File.OpenRead("Fonts/OpenSans-Regular.ttf")) face = new FontFace(stream); Console.WriteLine(face.Family); // "Open Sans" Console.WriteLine(face.FullName); // "Open Sans Regular" Console.WriteLine(face.Weight); // FontWeight.Normal Console.WriteLine(face.Style); // FontStyle.Regular Console.WriteLine(face.IsFixedWidth); // false ``` -------------------------------- ### Implement IGlyphAtlas and use TextAnalyzer Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Implement IGlyphAtlas to integrate with your graphics system. TextAnalyzer then processes text runs, computes glyph positions, and prepares for drawing. ```csharp // 1. Implement IGlyphAtlas to feed glyph bitmaps into your graphics system class MyAtlas : IGlyphAtlas { public int Width => 2048; public int Height => 2048; // Called once per unique glyph; 'data' is an 8-bit grayscale coverage bitmap public unsafe void Insert (int page, int x, int y, int w, int h, IntPtr data) { // e.g., upload sub-region to a GPU texture // UploadTexture(page, x, y, w, h, (byte*)data); } } // 2. Build analyzer, format, and layout objects var atlas = new MyAtlas(); var analyzer = new TextAnalyzer(atlas) { Dpi = 96 }; var format = new TextFormat { Font = FontCollection.SystemFonts.Load("Segoe UI"), Size = 11f }; var layout = new TextLayout(); // 3. Append text (supports multiple consecutive runs with different formats) analyzer.AppendText("Hello, ", format); analyzer.AppendText("World!", new TextFormat { Font = FontCollection.SystemFonts.Load("Segoe UI"), Size = 11f, Style = TextStyle.Underline }); // 4. Compute screen positions inside a 800×600 viewport starting at (10, 50) analyzer.PerformLayout(x: 10f, y: 50f, width: 800f, height: 600f, layout); // 5. Draw each glyph quad using layout data foreach (var entry in layout.Stuff) { // entry.DestX / DestY → screen position // entry.SourceX / SourceY / Width / Height → atlas sub-rectangle // DrawQuad(entry.DestX, entry.DestY, entry.SourceX, entry.SourceY, // entry.Width, entry.Height); } // 6. Clear buffer before the next frame analyzer.Clear(); ``` -------------------------------- ### TextFormat Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Defines how text should be rendered by bundling font face, point size, tab stop width, text decorations, alignment, and word-wrap settings. ```APIDOC ## TextFormat — Describe how text should be rendered `TextFormat` bundles together the `FontFace`, point size, tab-stop width, text decorations (`TextStyle`), alignment, and word-wrap settings that `TextAnalyzer` uses when processing a string. ```csharp var format = new TextFormat { Font = collection.Load("Open Sans"), Size = 14f, // in points; converted to px by TextAnalyzer via Dpi TabStop = 40f, Style = TextStyle.None, // or TextStyle.Underline | TextStyle.Strikeout LineAlignment = TextAlignment.Near, // Near=left, Center, Far=right ParagraphAlignment = TextAlignment.Near, WordWrap = BreakDelimiter.Word, Trimming = BreakDelimiter.None, }; ``` ``` -------------------------------- ### Describe Text Rendering Format Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Define TextFormat to bundle font face, point size, tab stops, text decorations, alignment, and word-wrap settings. TextAnalyzer uses this format for processing strings. ```csharp var format = new TextFormat { Font = collection.Load("Open Sans"), Size = 14f, // in points; converted to px by TextAnalyzer via Dpi TabStop = 40f, Style = TextStyle.None, // or TextStyle.Underline | TextStyle.Strikeout LineAlignment = TextAlignment.Near, // Near=left, Center, Far=right ParagraphAlignment = TextAlignment.Near, WordWrap = BreakDelimiter.Word, Trimming = BreakDelimiter.None, }; ``` -------------------------------- ### Manage and Look Up Fonts in a Collection Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Use FontCollection to manage fonts keyed by family, weight, stretch, and style. Fonts can be added from files, streams, or enumerated from the system. Load() returns a usable FontFace. InvalidFontException is thrown for corrupt files. ```csharp // --- Using the system font collection (Windows only) --- FontFace verdana = FontCollection.SystemFonts.Load("Verdana"); FontFace verdanaBold = FontCollection.SystemFonts.Load( "Verdana", weight: FontWeight.Bold, style: FontStyle.Regular); // --- Building a custom collection from files --- var collection = new FontCollection(); collection.AddFontFile("Fonts/OpenSans-Regular.ttf"); collection.AddFontFile("Fonts/SourceSansPro-Regular.otf"); // Add from a stream (e.g. embedded resource) using (var stream = typeof(Program).Assembly .GetManifestResourceStream("MyApp.Fonts.Roboto-Italic.ttf")) { collection.AddFontFile(stream); } FontFace openSans = collection.Load("Open Sans"); if (openSans == null) Console.Error.WriteLine("Font family not found"); // InvalidFontException is thrown by AddFontFile when the file has no name metadata try { collection.AddFontFile("corrupt.ttf"); } catch (InvalidFontException ex) { Console.Error.WriteLine($"Bad font: {ex.Message}"); } ``` -------------------------------- ### Convert Point Size to Pixels Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Static helper to convert typographic point sizes to pixel sizes based on screen DPI. Standard DPI is 96, with higher values for high-DPI screens. ```csharp float pixelSize = FontFace.ComputePixelSize(pointSize: 12f, dpi: 96); // 12pt @ 96 DPI → 16 px float hiDpi = FontFace.ComputePixelSize(12f, 192); // 12pt @ 192 DPI → 32 px (retina) ``` -------------------------------- ### Query Global Font Metrics Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Retrieves FaceMetrics scaled to a specific pixel size. Use these values for positioning baselines, line boxes, and drawing text decorations. ```csharp float px = FontFace.ComputePixelSize(14f, 96); // 18.67 px FaceMetrics m = face.GetFaceMetrics(px); Console.WriteLine($"Ascent: {m.CellAscent:F2}"); // distance baseline → top of em Console.WriteLine($"Descent: {m.CellDescent:F2}"); // distance baseline → bottom of em Console.WriteLine($"Line height: {m.LineHeight:F2}"); // recommended line-to-line spacing Console.WriteLine($"Cap height: {m.CapHeight:F2}"); // height of uppercase 'H' Console.WriteLine($"x-height: {m.XHeight:F2}"); // height of lowercase 'x' Console.WriteLine($"Underline pos: {m.UnderlinePosition:F2}"); // negative = below baseline Console.WriteLine($"Underline size: {m.UnderlineSize:F2}"); Console.WriteLine($"Strikeout pos: {m.StrikeoutPosition:F2}"); Console.WriteLine($"Strikeout size: {m.StrikeoutSize:F2}") ``` -------------------------------- ### Work with Unicode CodePoints Source: https://context7.com/mikepopoloski/sharpfont/llms.txt CodePoint abstracts Unicode scalar values, supporting implicit conversion from char and explicit conversion from integers or surrogate pairs. Used for character identity in SharpFont. ```csharp // From a regular BMP character (implicit) CodePoint cp1 = 'A'; // From a supplementary-plane character (surrogate pair) string emoji = "😀"; // U+1F600 CodePoint cp2 = new CodePoint(emoji[0], emoji[1]); // From a raw codepoint integer (explicit cast) CodePoint cp3 = (CodePoint)0x1F600; // Comparison Console.WriteLine(cp1 < cp3); // true Console.WriteLine(cp1 == 'A'); // true // Use with FontFace Glyph g = face.GetGlyph(cp2, pixelSize: 48f); if (g == null) Console.WriteLine("Emoji not supported by this font"); ``` -------------------------------- ### Render glyphs to a Surface Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Use the Surface value type to provide a raw buffer for glyph rendering. Supports direct memory access and optional row padding for alignment. ```csharp unsafe { int w = glyph.RenderWidth, h = glyph.RenderHeight; byte[] buffer = new byte[w * h]; fixed (byte* ptr = buffer) { // zero buffer for (int i = 0; i < w * h; i++) ptr[i] = 0; glyph.RenderTo(new Surface { Bits = (IntPtr)ptr, Width = w, Height = h, Pitch = w }); // buffer now contains antialiased alpha data // Larger pitch values allow row padding / alignment: int alignedPitch = (w + 3) & ~3; // 4-byte row alignment byte[] padded = new byte[alignedPitch * h]; fixed (byte* dst = padded) { glyph.RenderTo(new Surface { Bits = (IntPtr)dst, Width = w, Height = h, Pitch = alignedPitch }); } } } ``` -------------------------------- ### FontFace.ComputePixelSize Source: https://context7.com/mikepopoloski/sharpfont/llms.txt A static helper method to convert typographic point sizes to pixel sizes based on the provided DPI. This is essential for rendering text at the correct scale on different screens. ```APIDOC ## FontFace.ComputePixelSize — Convert point size to pixels Static helper that converts a typographic point size and a screen DPI into a pixel size suitable for all other `FontFace` methods. Standard desktop DPI is 96; high-DPI screens use 144 or 192. ```csharp float pixelSize = FontFace.ComputePixelSize(pointSize: 12f, dpi: 96); // 12pt @ 96 DPI → 16 px float hiDpi = FontFace.ComputePixelSize(12f, 192); // 12pt @ 192 DPI → 32 px (retina) ``` ``` -------------------------------- ### FontCollection Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Manages a set of fonts, allowing them to be indexed by family name, weight, stretch, and style. Fonts can be added individually or enumerated from the system's font directory. ```APIDOC ## FontCollection — Manage and look up a set of fonts `FontCollection` acts as an index of fonts keyed by family name, weight, stretch, and style. Fonts can be added individually (by stream or file path) or the static `SystemFonts` property enumerates all `.ttf` / `.otf` files from the OS fonts directory. `Load()` returns a ready-to-use `FontFace`. ```csharp // --- Using the system font collection (Windows only) --- FontFace verdana = FontCollection.SystemFonts.Load("Verdana"); FontFace verdanaBold = FontCollection.SystemFonts.Load( "Verdana", weight: FontWeight.Bold, style: FontStyle.Regular); // --- Building a custom collection from files --- var collection = new FontCollection(); collection.AddFontFile("Fonts/OpenSans-Regular.ttf"); collection.AddFontFile("Fonts/SourceSansPro-Regular.otf"); // Add from a stream (e.g. embedded resource) using (var stream = typeof(Program).Assembly .GetManifestResourceStream("MyApp.Fonts.Roboto-Italic.ttf")) { collection.AddFontFile(stream); } FontFace openSans = collection.Load("Open Sans"); if (openSans == null) Console.Error.WriteLine("Font family not found"); // InvalidFontException is thrown by AddFontFile when the file has no name metadata try { collection.AddFontFile("corrupt.ttf"); } catch (InvalidFontException ex) { Console.Error.WriteLine($"Bad font: {ex.Message}"); } ``` ``` -------------------------------- ### FontFace.GetKerning Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Retrieves the kerning adjustment between two characters. This is used to fine-tune the horizontal spacing between specific character pairs. ```APIDOC ## FontFace.GetKerning — Retrieve kerning adjustment between two characters Queries the font's kern table for the horizontal spacing correction to apply between a left and right character. Returns 0 if the font has no kern table or the pair is not listed. ```csharp float px = FontFace.ComputePixelSize(16f, 96); float kern = face.GetKerning('A', 'V', px); // Negative value: move 'V' closer to 'A' Console.WriteLine($"A–V kerning: {kern:F2} px"); // Typical usage in a manual text layout loop: float penX = 0f; string text = "AV"; for (int i = 0; i < text.Length; i++) { if (i > 0) penX += face.GetKerning(text[i - 1], text[i], px); Glyph g = face.GetGlyph(text[i], px); if (g != null) { // render g at penX + g.HorizontalMetrics.Bearing.X penX += g.HorizontalMetrics.Advance; } } ``` ``` -------------------------------- ### Rasterize a Single Character Glyph Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Obtain a Glyph object for a specific Unicode character at a given pixel size. The Glyph can then be rendered into a provided Surface. Ensure proper memory management for the allocated buffer. ```csharp using System.Runtime.InteropServices; float px = FontFace.ComputePixelSize(32f, 96); // 32pt @ 96 DPI Glyph glyph = face.GetGlyph('A', px); if (glyph != null) { Console.WriteLine($"Render size: {glyph.RenderWidth} × {glyph.RenderHeight} px"); Console.WriteLine($"Advance: {glyph.HorizontalMetrics.Advance:F2} px"); Console.WriteLine($"Bearing: {glyph.HorizontalMetrics.Bearing}"); // Allocate an 8-bit grayscale buffer and rasterize into it int stride = glyph.RenderWidth; IntPtr bits = Marshal.AllocHGlobal(stride * glyph.RenderHeight); try { // Zero the buffer unsafe { byte* p = (byte*)bits; for (int i = 0; i < stride * glyph.RenderHeight; i++) *p++ = 0; } glyph.RenderTo(new Surface { Bits = bits, Width = glyph.RenderWidth, Height = glyph.RenderHeight, Pitch = stride // bytes per row (= width for 8-bit grayscale) }); // 'bits' now contains antialiased coverage values (0–255) ready for upload // to a GPU texture or blending into a System.Drawing bitmap. } finally { Marshal.FreeHGlobal(bits); } } ``` -------------------------------- ### Retrieve Kerning Adjustment Between Characters Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Query the font's kern table for horizontal spacing adjustments between two characters. Returns 0 if no kern table exists or the pair is not found. This is useful for manual text layout. ```csharp float px = FontFace.ComputePixelSize(16f, 96); float kern = face.GetKerning('A', 'V', px); // Negative value: move 'V' closer to 'A' Console.WriteLine($"A–V kerning: {kern:F2} px"); // Typical usage in a manual text layout loop: float penX = 0f; string text = "AV"; for (int i = 0; i < text.Length; i++) { if (i > 0) penX += face.GetKerning(text[i - 1], text[i], px); Glyph g = face.GetGlyph(text[i], px); if (g != null) { // render g at penX + g.HorizontalMetrics.Bearing.X penX += g.HorizontalMetrics.Advance; } } ``` -------------------------------- ### FontFace.GetFaceMetrics Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Queries global font metrics for a given pixel size. This method returns a `FaceMetrics` object containing vertical measurements like ascent, descent, line height, and cap height, scaled to the specified pixel size. ```APIDOC ## FontFace.GetFaceMetrics — Query global font metrics at a size Returns a `FaceMetrics` object with all vertical measurements scaled to the requested pixel size. Use these values to position baselines, size line boxes, and draw underline / strikeout decorations. ```csharp float px = FontFace.ComputePixelSize(14f, 96); // 18.67 px FaceMetrics m = face.GetFaceMetrics(px); Console.WriteLine($"Ascent: {m.CellAscent:F2}"); // distance baseline → top of em Console.WriteLine($"Descent: {m.CellDescent:F2}"); // distance baseline → bottom of em Console.WriteLine($"Line height: {m.LineHeight:F2}"); // recommended line-to-line spacing Console.WriteLine($"Cap height: {m.CapHeight:F2}"); // height of uppercase 'H' Console.WriteLine($"x-height: {m.XHeight:F2}"); // height of lowercase 'x' Console.WriteLine($"Underline pos: {m.UnderlinePosition:F2}"); // negative = below baseline Console.WriteLine($"Underline size: {m.UnderlineSize:F2}"); Console.WriteLine($"Strikeout pos: {m.StrikeoutPosition:F2}"); Console.WriteLine($"Strikeout size: {m.StrikeoutSize:F2}"); ``` ``` -------------------------------- ### FontFace.GetGlyph Source: https://context7.com/mikepopoloski/sharpfont/llms.txt Rasterizes a single character to obtain a Glyph object. The Glyph object contains rendering dimensions and metrics, and can be blitted into a caller-allocated Surface. ```APIDOC ## FontFace.GetGlyph — Rasterize a single character Returns a `Glyph` object for the Unicode code point at the given pixel size, or `null` if the font does not contain the character. The `Glyph` exposes its render dimensions and `HorizontalMetrics` (bearing and advance) and can blit itself into any caller-allocated `Surface`. ```csharp using System.Runtime.InteropServices; float px = FontFace.ComputePixelSize(32f, 96); // 32pt @ 96 DPI Glyph glyph = face.GetGlyph('A', px); if (glyph != null) { Console.WriteLine($"Render size: {glyph.RenderWidth} × {glyph.RenderHeight} px"); Console.WriteLine($"Advance: {glyph.HorizontalMetrics.Advance:F2} px"); Console.WriteLine($"Bearing: {glyph.HorizontalMetrics.Bearing}"); // Allocate an 8-bit grayscale buffer and rasterize into it int stride = glyph.RenderWidth; IntPtr bits = Marshal.AllocHGlobal(stride * glyph.RenderHeight); try { // Zero the buffer unsafe { byte* p = (byte*)bits; for (int i = 0; i < stride * glyph.RenderHeight; i++) *p++ = 0; } glyph.RenderTo(new Surface { Bits = bits, Width = glyph.RenderWidth, Height = glyph.RenderHeight, Pitch = stride // bytes per row (= width for 8-bit grayscale) }); // 'bits' now contains antialiased coverage values (0–255) ready for upload // to a GPU texture or blending into a System.Drawing bitmap. } finally { Marshal.FreeHGlobal(bits); } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.