### Install SwiftDraw via Homebrew Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Installs the SwiftDraw command-line tool on macOS using Homebrew. Ensure Homebrew is already installed. ```bash $ brew install swiftdraw ``` -------------------------------- ### Example: Generate and Save PDF from SVG Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/cgcontext-extensions.md Shows how to generate PDF data from an SVG file and write it to a specified file URL. Includes error handling for the PDF generation and file writing process. ```swift let svg = SVG(named: "document.svg")! do { let pdfData = try svg.pdfData() try pdfData.write(to: fileURL) } catch { print("PDF generation failed: \(error)") } ``` -------------------------------- ### Configuring SVGView Resizing Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/types.md Example of setting the resizing mode for an SVGView. Adjust the frame to the desired dimensions. ```swift SVGView("pattern.svg") .resizable(resizingMode: .tile) .frame(width: 400, height: 300) ``` -------------------------------- ### Example SVG Input Source: https://github.com/swhitty/swiftdraw/blob/main/README.md This is an example SVG file that can be used as input for SwiftDraw. ```xml ``` -------------------------------- ### SwiftUI Generated Code Example Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md An example of the Swift struct generated for SwiftUI, featuring a Canvas for drawing. ```swift struct IconView: View { var body: some View { Canvas(opaque: false) { context, size in // Drawing commands here } .frame(width: 100, height: 100) } } ``` -------------------------------- ### Drawing with Insets Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/types.md Example of creating and using SVG.Insets for drawing context. Ensure the rect and context are properly defined. ```swift let insets = SVG.Insets(top: 10, left: 10, bottom: 10, right: 10) context.draw(svg, in: rect, capInsets: (top: insets.top, left: insets.left, bottom: insets.bottom, right: insets.right)) ``` -------------------------------- ### Responsive Sizing with Padding Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/transformations.md Create responsive elements by applying padding to an SVG before rasterizing it. This example adds specific padding to the top, bottom, left, and right edges. ```swift let icon = SVG(named: "button-icon.svg")! // 48x48 let padded = icon.expanded(left: 8, right: 8, top: 4, bottom: 4) // 64x56 let rasterized = padded.rasterize() ``` -------------------------------- ### Update SwiftDraw via Homebrew Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Updates an existing SwiftDraw installation to the latest version using Homebrew. ```bash $ brew upgrade swiftdraw ``` -------------------------------- ### Transformation Order and Composition Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/transformations.md Chained transformations are applied in composition order, with the innermost transformation executed first. This example demonstrates scaling, padding, and translation. ```swift let svg = SVG(named: "base.svg")! // 100x100 let result = svg .scaled(2.0) // Applied third: scale by 2x .expanded(10) // Applied second: add 10pt padding .translated(5, 5) // Applied first: translate // Effective size: ((100 + 10*2) * 2) = 240x240 // Content is translated, then padded, then scaled ``` -------------------------------- ### SVG Caching Example Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Demonstrates SVGView's internal caching mechanism. Repeated uses of the same filename reuse the parsed SVG object for efficiency. To bypass caching, initialize with a pre-parsed SVG instance. ```swift // These reuse the cached SVG (efficient) VStack { SVGView("icon.svg") SVGView("icon.svg") } // Bypass cache with pre-loaded SVG let svg = SVG(named: "icon.svg")! VStack { SVGView(svg: svg) SVGView(svg: svg) } ``` -------------------------------- ### Export SVG to Image Data Formats Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Examples for exporting SVG content into PNG, JPEG, and PDF data formats with specified scaling and compression. ```swift // PNG let pngData = try svg.pngData(scale: 2.0) // JPEG let jpegData = try svg.jpegData(scale: 2.0, compressionQuality: 0.8) // PDF let pdfData = try svg.pdfData() ``` -------------------------------- ### Handle SVG Loading and Export Errors Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Provides examples of error handling for SVG loading failures and export operation errors. ```swift guard let svg = SVG(named: "icon.svg") else { print("Failed to load SVG") return } do { let data = try svg.pngData() } catch { print("Export failed: \(error)") } ``` -------------------------------- ### Convert SVG to SF Symbol with Optional Variants Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Generate SF Symbols with optional ultralight and black variants by providing specific SVG files for each or using command-line flags. This example shows providing explicit files for variants. ```bash $ swiftdraw [key.svg](https://github.com/swhitty/SwiftDraw/blob/main/Samples.bundle/key/key.svg) --format sfsymbol --ultralight [key-ultralight.svg](https://github.com/swhitty/SwiftDraw/blob/main/Samples.bundle/key/key-ultralight.svg) --black [key-black.svg](https://github.com/swhitty/SwiftDraw/blob/main/Samples.bundle/key/key-black.svg) ``` -------------------------------- ### Specify Output Format Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Demonstrates how to explicitly set the desired output format for the conversion using the --format option. ```bash swiftdraw input.svg --format ``` -------------------------------- ### init(named:in:options:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Initializes an SVG instance by loading it as a resource from a specified bundle. It allows specifying the bundle and parsing options, returning an optional SVG instance or nil if the resource is not found. ```APIDOC ## init(named:in:options:) ### Description Loads an SVG from a bundle by resource name. ### Method `init` (Initializer) ### Parameters #### Path Parameters - **name** (`String`) - Required - Resource name (with or without .svg extension) - **bundle** (`Bundle`) - Optional - Bundle to search for resource - **options** (`SVG.Options`) - Optional - Parser options ### Response #### Success Response - **SVG?** - Initialized SVG instance, or `nil` if resource not found. ### Example ```swift if let svg = SVG(named: "logo.svg", in: Bundle.main) { imageView.image = svg.rasterize() } ``` ``` -------------------------------- ### init(fileURL:options:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Initializes an SVG instance by loading it from a specified file URL. It supports optional parsing options and returns an optional SVG instance, or nil if the file cannot be found or parsed. ```APIDOC ## init(fileURL:options:) ### Description Loads an SVG from a file URL with optional caching. ### Method `init` (Initializer) ### Parameters #### Path Parameters - **url** (`URL`) - Required - File URL pointing to an SVG file - **options** (`SVG.Options`) - Optional - Parser options (e.g., `hideUnsupportedFilters`) ### Response #### Success Response - **SVG?** - Initialized SVG instance, or `nil` if parsing fails or file not found. ### Example ```swift if let svg = SVG(fileURL: URL(fileURLWithPath: "/path/to/image.svg")) { let image = svg.rasterize() } ``` ``` -------------------------------- ### Default Bundle Resource Loading Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/configuration.md Resource loading methods default to using `Bundle.main`. To load from a specific bundle, provide the bundle explicitly. ```swift // Loads from Bundle.main SVGView("icon.svg") SVG(named: "icon.svg") UIImage(svgNamed: "icon.svg") NSImage(svgNamed: "icon.svg") // Load from specific bundle SVGView("icon.svg", bundle: myBundle) SVG(named: "icon.svg", in: myBundle) ``` -------------------------------- ### init(data:options:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Initializes an SVG instance from raw Data, typically obtained from file I/O or network responses. It supports optional parsing options and returns an optional SVG instance or nil if parsing fails. ```APIDOC ## init(data:options:) ### Description Creates an SVG from Data (typically loaded from a file or network). ### Method `init` (Initializer) ### Parameters #### Path Parameters - **data** (`Data`) - Required - SVG file as Data - **options** (`SVG.Options`) - Optional - Parser options ### Response #### Success Response - **SVG?** - Initialized SVG instance, or `nil` if parsing fails. ### Example ```swift let data = try Data(contentsOf: fileURL) if let svg = SVG(data: data) { let image = svg.rasterize() } ``` ``` -------------------------------- ### SVGView Initialization with Name Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Initializes an SVGView by loading an SVG resource from a specified bundle. Defaults to the main bundle. ```APIDOC ## init(_:bundle:) ### Description Create an SVGView by loading an SVG resource from a bundle. ### Parameters #### Path Parameters - **name** (`String`) - Required - SVG resource name - **bundle** (`Bundle`) - Optional - Bundle to search for resource (Defaults to `.main`) ### Example ```swift import SwiftUI import SwiftDraw struct ContentView: View { var body: some View { SVGView("logo.svg") } } ``` ``` -------------------------------- ### init(xml:options:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Initializes an SVG instance directly from an XML string. This is useful for dynamically generated SVG content. It accepts optional parsing options and returns an optional SVG instance or nil if parsing fails. ```APIDOC ## init(xml:options:) ### Description Creates an SVG from an XML string. ### Method `init` (Initializer) ### Parameters #### Path Parameters - **xml** (`String`) - Required - SVG XML as string - **options** (`SVG.Options`) - Optional - Parser options ### Response #### Success Response - **SVG?** - Initialized SVG instance, or `nil` if parsing fails. ### Example ```swift let svgString = """ """ if let svg = SVG(xml: svgString) { // Use svg } ``` ``` -------------------------------- ### Get SVG Intrinsic Size Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Access the intrinsic size of the SVG canvas as defined in the document. The size is represented as a CGSize, indicating width and height in points. ```swift public private(set) var size: CGSize ``` -------------------------------- ### init(contentsOfSVGFile:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/uiimage-extensions.md Creates a UIImage by loading an SVG file directly from a specified file path. Useful for SVGs stored locally on the device. ```APIDOC ## init(contentsOfSVGFile:) ### Description Create a UIImage from an SVG file path. ### Method `convenience init` ### Parameters #### Path Parameters - **path** (String) - Required - Absolute file path to SVG file ### Response #### Success Response - **UIImage?** – Rasterized image, or nil if file not found or parsing fails. ### Request Example ```swift let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let svgPath = (path as NSString).appendingPathComponent("image.svg") if let image = UIImage(contentsOfSVGFile: svgPath) { imageView.image = image } ``` ``` -------------------------------- ### init(svgNamed:in:options:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/uiimage-extensions.md Creates a UIImage from an SVG resource loaded from a bundle. Supports specifying the SVG name, the bundle to load from, and parsing options. ```APIDOC ## init(svgNamed:in:options:) ### Description Create a UIImage from an SVG resource loaded from a bundle. ### Method `convenience init` ### Parameters #### Path Parameters - **name** (String) - Required - SVG resource name - **bundle** (Bundle) - Optional - Bundle containing the SVG file (Defaults to .main) - **options** (SVG.Options) - Optional - Parser options (Defaults to .default) ### Response #### Success Response - **UIImage?** – Rasterized image, or nil if SVG not found or parsing fails. ### Request Example ```swift import UIKit import SwiftDraw let image = UIImage(svgNamed: "icon.svg") imagView.image = image ``` ``` -------------------------------- ### Auto-align SF Symbol with 'auto' Insets Source: https://github.com/swhitty/swiftdraw/blob/main/README.md SwiftDraw automatically sizes and aligns SVG content to template guides. Use `--insets auto` to let the tool determine optimal alignment values. ```bash $ swiftdraw simple.svg --format sfsymbol --insets auto Alignment: --insets 30,30,30,30 ``` -------------------------------- ### init(contentsOfSVGFile:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Initializes an NSImage by loading an SVG file from a given absolute file path. This method is suitable when the SVG file is directly accessible on the filesystem. ```APIDOC ## init(contentsOfSVGFile:) ### Description Create an NSImage from an SVG file path. ### Method `init` (convenience constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (`String`) - Required - Absolute file path to SVG file ### Response #### Success Response `NSImage?` – Rasterized image. #### Error Response `nil` – If file not found or parsing fails. ### Example ```swift let svgPath = "/Users/user/Documents/icon.svg" if let image = NSImage(contentsOfSVGFile: svgPath) { imageView.image = image } ``` ``` -------------------------------- ### Load SVG from Various Sources Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Demonstrates loading an SVG from different sources like bundle, file, data, or an XML string. ```swift // From bundle let svg = SVG(named: "icon.svg") // From file let svg = SVG(fileURL: url) // From data let svg = SVG(data: data) // From XML string let svg = SVG(xml: svgString) ``` -------------------------------- ### init(svgNamed:in:options:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Initializes an NSImage from an SVG resource located by name within a specified bundle. It allows for custom parser options and defaults to using the main bundle and default options. ```APIDOC ## init(svgNamed:in:options:) ### Description Create an NSImage from an SVG resource loaded from a bundle. ### Method `init` (convenience constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (`String`) - Required - SVG resource name - **bundle** (`Bundle`) - Optional - Bundle containing the SVG file (Defaults to `.main`) - **options** (`SVG.Options`) - Optional - Parser options (Defaults to `.default`) ### Response #### Success Response `NSImage?` – Rasterized image. #### Error Response `nil` – If SVG not found or parsing fails. ### Example ```swift import AppKit import SwiftDraw let image = NSImage(svgNamed: "icon.svg") imageView.image = image ``` ``` -------------------------------- ### Apply Insets (Padding) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Add padding or crop edges of the output using the --insets option. Values can be fixed pixel amounts or 'auto' for SF Symbol-like behavior. ```bash swiftdraw input.svg --insets top,left,bottom,right ``` ```bash swiftdraw icon.svg --insets 10,10,10,10 # 10pt on all sides ``` ```bash swiftdraw icon.svg --insets 0,20,0,20 # 20pt on left/right ``` -------------------------------- ### Initialize SVGView with SVG Instance Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Create an SVGView directly from a pre-loaded SVG instance. This is useful to avoid repeated loading and parsing of the same SVG file, enhancing performance. ```swift public init(svg: SVG) ``` ```swift @State var svg = SVG(named: "icon.svg")! var body: some View { SVGView(svg: svg) .resizable() .scaledToFit() } ``` -------------------------------- ### Initialize SVGView with SVG Name Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Create an SVGView by loading an SVG resource from a specified bundle. Use this for basic SVG loading from your project's assets. ```swift public init(_ name: String, bundle: Bundle = .main) ``` ```swift import SwiftUI import SwiftDraw struct ContentView: View { var body: some View { SVGView("logo.svg") } } ``` -------------------------------- ### Multi-Scale PNG Asset Generation Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Generate PNG assets at multiple scales (@1x, @2x, @3x) using a loop. ```bash # Generate @1x, @2x, @3x for scale in 1x 2x 3x; do swiftdraw icon.svg --format png --scale $scale --output icon@${scale}.png done ``` -------------------------------- ### SVGView Initialization with SVG Instance Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Initializes an SVGView using a pre-loaded SVG instance. This is useful for avoiding repeated loading and parsing. ```APIDOC ## init(svg:) ### Description Create an SVGView from a pre-loaded SVG instance. Use this to avoid repeated loading and parsing. ### Parameters #### Path Parameters - **svg** (`SVG`) - Required - Pre-loaded SVG instance ### Example ```swift @State var svg = SVG(named: "icon.svg")! var body: some View { SVGView(svg: svg) .resizable() .scaledToFit() } ``` ``` -------------------------------- ### SwiftDraw Module Dependencies Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/modules-overview.md Illustrates the hierarchical structure of SwiftDraw's public and internal modules, showing how different components depend on each other. ```text Applications ↓ SwiftDraw (Public) ├── SVG struct ├── SVGView (SwiftUI) ├── UIImage extensions ├── NSImage extensions ├── CGContext extensions ├── LayerTree (internal) ├── Renderer (internal) ├── Formatter (internal) └── SwiftDrawDOM (internal) ├── XML Parser ├── DOM Types └── SVG Elements ``` -------------------------------- ### init(svgData:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/uiimage-extensions.md Creates a UIImage from SVG data, typically obtained from network requests or file operations. Handles parsing of SVG content directly from Data. ```APIDOC ## init(svgData:) ### Description Create a UIImage from SVG data (typically from a network request or file). ### Method `convenience init` ### Parameters #### Path Parameters - **svgData** (Data) - Required - SVG file as Data ### Response #### Success Response - **UIImage?** – Rasterized image, or nil if parsing fails. ### Request Example ```swift let data = try Data(contentsOf: url) if let image = UIImage(svgData: data) { imageView.image = image } ``` ``` -------------------------------- ### Basic SwiftDraw Command Structure Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md The fundamental structure for using the swiftdraw command, specifying an input SVG file and optional format or other arguments. ```bash swiftdraw [--format ] [options] ``` -------------------------------- ### Initialize SVG from Data Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Initialize an SVG instance from raw Data, typically obtained from file I/O or network responses. This method is flexible for handling SVG content in various data formats. Parsing will fail and return nil if the data is malformed. ```swift public init?(data: Data, options: SVG.Options = .default) let data = try Data(contentsOf: fileURL) if let svg = SVG(data: data) { let image = svg.rasterize() } ``` -------------------------------- ### Command Line Interface for SVG Operations Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Demonstrates using the SwiftDraw command-line tool for exporting SVGs to various formats and generating Swift code. ```bash # PNG export swiftdraw icon.svg --format png --scale 2x # PDF export swiftdraw document.svg --format pdf # Swift code generation swiftdraw icon.svg --format swift --api swiftui # SF Symbol swiftdraw symbol.svg --format sfsymbol --insets auto ``` -------------------------------- ### init(_:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Initializes an NSImage directly from SVG data. This is useful when SVG content is available as a Data object, for instance, after being read from a file or received over a network. ```APIDOC ## init(_:) ### Description Create an NSImage from SVG data. ### Method `init` (convenience constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **data** (`Data`) - Required - SVG file as Data ### Response #### Success Response `NSImage?` – Rasterized image. #### Error Response `nil` – If parsing fails. ### Example ```swift let data = try Data(contentsOf: url) if let image = NSImage(data) { imageView.image = image } ``` ``` -------------------------------- ### Set Output Scale Factor Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Adjust the output resolution using the --scale option, which is useful for generating assets for different screen densities (e.g., 1x, 2x, 3x). ```bash swiftdraw input.svg --scale 2x ``` ```bash swiftdraw icon.svg --format png --scale 3x --output icon@3x.png ``` -------------------------------- ### Module Dependencies Diagram Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Illustrates the module dependencies within the SwiftDraw project, showing the flow from the user application down to internal components and the Swift Standard Library. This highlights the project's self-contained nature with no external library dependencies. ```text User Application ↓ Public API: SVG, SVGView, Extensions ↓ Internal: LayerTree, Renderer, Formatter ↓ Internal: SwiftDrawDOM (XML parsing) ``` -------------------------------- ### Handling Optional SVG Loading Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/types.md Demonstrates checking for successful SVG loading or parsing. Initializers return nil on failure. ```swift if let svg = SVG(named: "icon.svg") { // Success } else { // Failed to load or parse } ``` -------------------------------- ### Chaining Immutable Transformations Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/transformations.md Demonstrates how to chain multiple immutable transformation methods. The original SVG instance remains unchanged after transformations. ```swift let original = SVG(named: "icon.svg")! let transformed = original .scaled(2.0) .expanded(10) .translated(tx: 5, ty: 5) // original remains unchanged ``` -------------------------------- ### Initialize SVG from File URL Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Load an SVG document from a specified file URL. This initializer supports optional caching and default parsing options. It returns an optional SVG instance, which will be nil if the file is not found or parsing fails. ```swift public init?(fileURL url: URL, options: SVG.Options = .default) if let svg = SVG(fileURL: URL(fileURLWithPath: "/path/to/image.svg")) { let image = svg.rasterize() } ``` -------------------------------- ### Provide Explicit Size for Output Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md When converting SVGs that omit dimensions or use percentages, provide explicit width and height using the --size argument. ```bash swiftdraw responsive.svg --format png --size 800x600 ``` -------------------------------- ### Convert SVG to Swift Source Code using Command Line Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/quick-start.md Generate Swift source code representing the SVG, suitable for use with SwiftUI or other Swift frameworks. The `--api swiftui` flag specifies the target API. ```bash swiftdraw icon.svg --format swift --api swiftui ``` -------------------------------- ### Implement Responsive SVGView Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Display an SVG within a view that automatically resizes to fit its container. This pattern is ideal for adaptive UIs. ```swift SVGView("responsive.svg") .resizable() .scaledToFit() .frame(maxWidth: .infinity, maxHeight: .infinity) ``` -------------------------------- ### Specify Output File Path Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Use the --output option to define a custom path and filename for the generated output file. If omitted, the output name is auto-generated based on the input file and format. ```bash swiftdraw input.svg --output /path/to/output.png ``` ```bash swiftdraw icon.svg --format png --output ~/Desktop/icon.png ``` -------------------------------- ### SwiftDrawDOM Parsing Pipeline Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/modules-overview.md Illustrates the data flow from an SVG file to rendering commands through the SwiftDrawDOM module and subsequent layers. ```text SVG File/Data ↓ XML Parser (DOM/Sources/Parser.XML.swift) ↓ DOM Tree (DOM/Sources/DOM*.swift) ↓ LayerTree Builder (SwiftDraw/Sources/LayerTree/) ↓ Rendering Commands (SwiftDraw/Sources/Renderer/) ↓ CGContext / Image ``` -------------------------------- ### Reload SVG File by Loading as Data Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/configuration.md Illustrates how to bypass the internal cache for SVGs loaded via `fileURL` by loading the content as `Data` and then initializing the SVG from that data. This is useful for ensuring the latest file content is used. ```swift let data = try Data(contentsOf: fileURL) let svg = SVG(data: data) ``` -------------------------------- ### Transform SVG Properties Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/README.md Illustrates common SVG transformations including scaling, padding, and translation. ```swift let transformed = svg .scaled(2.0) // 2x scale .expanded(10) // Add padding .translated(tx: 5, ty: 5) // Offset ``` -------------------------------- ### Generate Swift Code (SwiftUI) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Generate SwiftUI code for an icon from an SVG file. This is the default API if --api is omitted. ```bash swiftdraw icon.svg --format swift --api swiftui --output Icon.swift ``` -------------------------------- ### SwiftDraw Source File Organization Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/modules-overview.md Details the directory structure of the SwiftDraw library, including the location of core components, extensions, views, and internal modules. ```text SwiftDraw/ ├── Sources/ │ ├── SVG.swift # Core SVG struct │ ├── SVG+CoreGraphics.swift # CGContext extensions │ ├── SVG+UIKit.swift # UIKit compatibility │ ├── SVG+Insets.swift # Insets type │ ├── SVGView.swift # SwiftUI view │ ├── SVGCache.swift # Internal caching │ ├── UIImage+SVG.swift # UIKit extensions │ ├── NSImage+SVG.swift # AppKit extensions │ ├── CanvasUIView.swift # UIKit fallback │ ├── CanvasNSView.swift # AppKit fallback │ ├── LayerTree/ # Intermediate representation │ │ ├── LayerTree.swift │ │ ├── LayerTree.Builder.swift │ │ ├── LayerTree.CommandGenerator.swift │ │ ├── LayerTree.CommandOptimizer.swift │ │ └── ... │ ├── Renderer/ # Core Graphics rendering │ │ ├── Renderer.swift │ │ ├── Renderer.Command.swift │ │ └── ... │ ├── Formatter/ # Code generation │ │ └── ... │ ├── Utilities/ # Helpers │ │ └── ... │ └── WOFF/ # Font support │ └── ... │ └── Tests/ └── SwiftDrawTests/ DOM/ ├── Sources/ │ ├── DOM.swift # Type definitions │ ├── DOM.SVG.swift # Root element │ ├── DOM.Element.swift # Element types │ ├── DOM.Color.swift # Color handling │ ├── DOM.Path.swift # Path data │ ├── DOM.Text.swift # Text elements │ ├── DOM.Image.swift # Image elements │ ├── DOM.LinearGradient.swift # Gradients │ ├── DOM.RadialGradient.swift │ ├── DOM.Pattern.swift │ ├── DOM.Filter.swift │ ├── DOM.FontFace.swift │ ├── DOM.PresentationAttributes.swift # Styling │ ├── Parser.XML.swift # XML parsing │ ├── Parser.XML.*.swift # Element-specific parsers │ ├── XML.SAXParser.swift │ ├── XML.Element.swift │ └── ... │ └── Tests/ └── SwiftDrawDOMTests/ ``` -------------------------------- ### Create Multi-Weight SF Symbol Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Command to create an SF Symbol with multiple weights (ultralight, black) by providing separate SVG files and stroke widths. ```bash swiftdraw regular.svg --format sfsymbol \ --insets auto \ --ultralight ultralight.svg \ --ultralight-stroke-width 50% \ --black black.svg \ --black-stroke-width 2.0 \ --output symbol.svg ``` -------------------------------- ### sized(_:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/transformations.md Sets the SVG to a specific size by scaling proportionally while preserving the aspect ratio. ```APIDOC ## sized(_:) ### Description Sets the SVG to a specific size by scaling proportionally. The aspect ratio is preserved. ### Method `sized(_ s: CGSize) -> SVG` ### Parameters #### Path Parameters - **s** (`CGSize`) - Required - Target size (width, height) ### Returns `SVG` with new size ### Behavior Calculates scale factors (sx, sy) from the ratio of target size to current size, then applies uniform transformation. ### Example: ```swift let svg = SVG(named: "icon.svg")! // 100x100 let resized = svg.sized(CGSize(width: 200, height: 200)) // Result: 200x200 ``` ``` -------------------------------- ### Initialize SVG from XML String Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Create an SVG instance directly from an XML string. This initializer is convenient for dynamically generated SVGs or when SVGs are received as text. It returns nil if the provided XML string is invalid or cannot be parsed. ```swift public init?(xml: String, options: SVG.Options = .default) let svgString = """ """ if let svg = SVG(xml: svgString) { // Use svg } ``` -------------------------------- ### Button with Rounded Corners and Border using 9-Slice Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/cgcontext-extensions.md Demonstrates drawing a button template using 9-slice cap insets. This preserves corner radius while allowing the button to scale. Use this when you need scalable UI elements with defined border and corner areas. ```swift let buttonSVG = SVG(named: "button-template.svg")! let insets = (top: 20.0, left: 20.0, bottom: 20.0, right: 20.0) // Draw button at different sizes, preserving corner radius for size in [CGSize(100, 50), CGSize(200, 50), CGSize(300, 50)] { let rect = CGRect(origin: .zero, size: size) context.draw(buttonSVG, in: rect, capInsets: insets, byTiling: false) } ``` -------------------------------- ### Load SVG from File System Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/quick-start.md Load an SVG object directly from a file path on the file system by providing a URL to the SVG file. ```swift let url = URL(fileURLWithPath: "/path/to/image.svg") let svg = SVG(fileURL: url) ``` -------------------------------- ### Initialize SVG from Bundle Resource Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Load an SVG resource directly from an application bundle. You can specify the resource name and optionally the bundle to search. This is useful for including SVGs as part of your application assets. Returns nil if the resource cannot be found. ```swift public init?(named name: String, in bundle: Bundle = Bundle.main, options: SVG.Options = .default) if let svg = SVG(named: "logo.svg", in: Bundle.main) { imageView.image = svg.rasterize() } ``` -------------------------------- ### SVGView resizable Method Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Makes the SVGView resizable to fill available space, with options for 9-slice cap insets and resizing mode (stretch or tile). ```APIDOC ## resizable(capInsets:resizingMode:) ### Description Make the SVGView resizable to fill available space. ### Parameters #### Path Parameters - **capInsets** (`EdgeInsets`) - Optional - 9-slice cap insets for non-scaling edges (Defaults to zero insets) - **resizingMode** (`ResizingMode`) - Optional - How to fill space (stretch or tile) (Defaults to `.stretch`) ### Returns `Self` – Modified SVGView ### Example ```swift SVGView("background.svg") .resizable() .scaledToFit() ``` ``` -------------------------------- ### Handling Optional Image Creation Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/errors.md Use a `guard let` statement to safely unwrap the optional image returned by the initializer. This ensures your application handles cases where the SVG image cannot be loaded. ```swift guard let image = UIImage(svgNamed: "icon.svg") else { print("Failed to load SVG image") return } ``` -------------------------------- ### SwiftDraw Project File Structure Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/MANIFEST.md This is the directory structure for the generated SwiftDraw technical documentation. It lists all generated markdown files and their organization. ```markdown /workspace/home/output/ ├── MANIFEST.md (this file - analysis summary) ├── INDEX.md (complete file index and statistics) ├── README.md (main entry point and navigation) ├── quick-start.md (getting started guide) ├── types.md (all type definitions) ├── configuration.md (configuration options) ├── svg-features.md (supported SVG features) ├── errors.md (error handling reference) ├── modules-overview.md (architecture) ├── command-line-reference.md (CLI tool) └── api-reference/ (6 API reference documents) ├── svg-struct.md ├── svgview.md ├── uiimage-extensions.md ├── nsimage-extensions.md ├── cgcontext-extensions.md └── transformations.md ``` -------------------------------- ### Generate PDF Document Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Create a PDF document from an SVG file, preserving vector information for scalability. PDF output does not require rasterization. ```bash swiftdraw document.svg --format pdf --output document.pdf ``` -------------------------------- ### SF Symbol with Multiple Weights (Direct) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Create an SF Symbol with multiple weights by specifying the regular, ultralight, and black variants directly. ```bash swiftdraw symbol-regular.svg \ --format sfsymbol \ --insets auto \ --ultralight symbol-ultralight.svg \ --black symbol-black.svg \ --output MySymbol.svg ``` -------------------------------- ### _svgNamed(_:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Objective-C compatible static method to load SVG from the main bundle. ```APIDOC ## _svgNamed(_:) ### Description Objective-C compatible static method to load SVG from main bundle. ### Method `static func _svgNamed(_ name: String) -> NSImage?` ### Parameters #### Path Parameters - **name** (String) - Required - The name of the SVG file to load. ### Request Example ```objc NSImage *image = [NSImage _svgNamed:@"icon.svg"]; ``` ### Response #### Success Response - **NSImage?** - The loaded NSImage object, or nil if the SVG could not be loaded. ``` -------------------------------- ### Apply Transformations and Rasterize SVG Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Load an SVG, apply transformations like expansion and scaling, and then rasterize it to a UIImage. Transformations are applied sequentially. ```swift let svg = SVG(named: "fish.svg")! // 100x100 .expanded(left: 10, right: 10) // 120x100 .scaled(2) // 240x200 imageView.image = svg.rasterize() // 240x200 ``` -------------------------------- ### Absolute Sizing with sized(_:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/transformations.md Sets the SVG to a specific target size while preserving its aspect ratio. This method calculates the necessary uniform scale factor. ```swift let svg = SVG(named: "icon.svg")! // 100x100 let resized = svg.sized(CGSize(width: 200, height: 200)) // Result: 200x200 ``` -------------------------------- ### Load and Rasterize SVG to UIImage Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Load an SVG by name and rasterize it into a UIImage for display. Assumes the SVG is in the main bundle. ```swift let svg = SVG(named: "sample.svg", in: .main)! imageView.image = svg.rasterize() ``` -------------------------------- ### Load SVG by Name and Bundle (Objective-C) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/uiimage-extensions.md Objective-C compatible static method to load an SVG image from a specific bundle. ```swift @objc public static func _svgNamed(_ name: String, in bundle: Bundle) -> UIImage? ``` -------------------------------- ### Responsive SVG with Fixed Size PNG Export Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Export a responsive SVG to a PNG with explicit dimensions, necessary when the SVG's intrinsic size is 100%. ```bash # SVG with 100% dimensions needs explicit size swiftdraw responsive.svg --format png --size 800x600 --output responsive.png ``` -------------------------------- ### UIImage/NSImage Initializers Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/errors.md These initializers for creating UIImage or NSImage from SVG return an optional. They may return nil if the SVG fails to load, parse, or rasterize. ```swift public convenience init?(svgNamed name: String, in bundle: Bundle = .main, options: SVG.Options = .default) public convenience init?(svgData: Data) public convenience init?(contentsOfSVGFile path: String) ``` -------------------------------- ### Standard SVG Parsing Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/configuration.md Loads an SVG file using default parsing options, rendering all supported features. This is the basic usage for integrating SVGs. ```swift let svg1 = SVG(named: "icon.svg") ``` -------------------------------- ### Basic SVG to PNG Conversion Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Converts an SVG file to PNG format with a specified scale. Ensure the 'swiftdraw' command is in your PATH. ```bash $ swiftdraw simple.svg --format png --scale 3x ``` -------------------------------- ### Create UIImage from SVG Name Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/uiimage-extensions.md Use this initializer to create a UIImage from an SVG resource located within a specified bundle. Ensure the SVG file is correctly named and accessible. ```swift import UIKit import SwiftDraw let image = UIImage(svgNamed: "icon.svg") imageView.image = image ``` -------------------------------- ### Load SVG from Main Bundle (Objective-C) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Use this Objective-C compatible static method to load an SVG resource directly from the application's main bundle. ```objc NSImage *image = [NSImage _svgNamed:@"icon.svg"]; ``` -------------------------------- ### Provide Fallback Images Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/errors.md Implement fallback images to be used when SVG loading fails. This ensures a default image is displayed, improving user experience. ```swift let svg = SVG(named: "icon.svg") ?? SVG(named: "fallback.svg")! ``` -------------------------------- ### Thumbnail Generation Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/transformations.md Generate a thumbnail by resizing an SVG to specific dimensions and then rasterizing it to a bitmap image at a given scale. ```swift let original = SVG(named: "portrait.svg")! let thumbnail = original.sized(CGSize(width: 64, height: 64)) let image = thumbnail.rasterize(scale: 2.0) // 128x128 bitmap ``` -------------------------------- ### Generate Swift Code (AppKit) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Generate AppKit code for an icon from an SVG file. This uses NSGraphicsContext rendering. ```bash swiftdraw icon.svg --format swift --api appkit --output Icon.swift ``` -------------------------------- ### Generate PNG Image Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Use this command to convert an SVG file to a PNG image with specified scaling. PNG-specific options like scale and insets can be used. ```bash swiftdraw icon.svg --format png --scale 2x --output icon@2x.png ``` -------------------------------- ### _svgNamed(_:in:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Objective-C compatible static method to load SVG from a specific bundle. ```APIDOC ## _svgNamed(_:in:) ### Description Objective-C compatible static method to load SVG from a specific bundle. ### Method `static func _svgNamed(_ name: String, in bundle: Bundle) -> NSImage?` ### Parameters #### Path Parameters - **name** (String) - Required - The name of the SVG file to load. - **bundle** (Bundle) - Required - The bundle to load the SVG from. ### Response #### Success Response - **NSImage?** - The loaded NSImage object, or nil if the SVG could not be loaded. ``` -------------------------------- ### SVG.Options OptionSet Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/types.md Defines parser options for SVG parsing behavior. Use `.hideUnsupportedFilters` to hide unsupported filter effects. ```swift public struct Options: OptionSet { public let rawValue: Int public init(rawValue: Int) public static var hideUnsupportedFilters: Options { Options(rawValue: 1 << 0) } public static var `default`: Options { [] } } ``` -------------------------------- ### Display Pre-constructed SVG Instance in SwiftUI Source: https://github.com/swhitty/swiftdraw/blob/main/README.md Pass an already constructed SVG instance to SVGView for more predictable performance in SwiftUI, avoiding cache lookups. ```swift var image: SVG var body: some View { SVGView(svg: image) } ``` -------------------------------- ### Create Scaled SVG with Specific Size Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svg-struct.md Create a new SVG instance with a specified size, proportionally scaling its content. This is useful for fitting an SVG into a layout of a particular dimension. ```swift let svg = SVG(named: "icon.svg")!.sized(CGSize(width: 100, height: 100)) ``` -------------------------------- ### Create NSImage from SVG File Path Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Load an NSImage from an SVG file by providing its absolute path. Ensure the file exists and is accessible. ```swift public convenience init?(contentsOfSVGFile path: String) ``` ```swift let svgPath = "/Users/user/Documents/icon.svg" if let image = NSImage(contentsOfSVGFile: svgPath) { imageView.image = image } ``` -------------------------------- ### Load SVG from Data or String Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/quick-start.md Instantiate an SVG object from raw Data or an XML string. This is useful when SVG content is dynamically generated or fetched. ```swift // From Data let data = try Data(contentsOf: url) let svg = SVG(data: data) // From XML string let xmlString = """ """ let svg = SVG(xml: xmlString) ``` -------------------------------- ### GraphicsContext.draw(_:in:capInsets:byTiling:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/svgview.md Draws an SVG with support for 9-slice cap insets and optional tiling. Available on iOS 15+, macOS 12+, tvOS 15+, watchOS 8+. ```APIDOC ## GraphicsContext.draw(_:in:capInsets:byTiling:) ### Description Draw an SVG with 9-slice cap insets and optional tiling. ### Availability - iOS 15.0+ - macOS 12.0+ - tvOS 15.0+ - watchOS 8.0+ ### Parameters #### Path Parameters - **svg** (`SVG`) - Required - The SVG to draw - **rect** (`CGRect`) - Required - The rectangle to draw the SVG in - **capInsets** (`EdgeInsets`) - Required - 9-slice cap insets - **byTiling** (`Bool`) - Optional - Whether to tile the SVG (Defaults to `false`) ### Example ```swift // Example usage within a Canvas Canvas { context, size in if let svg = SVG(named: "tiled_pattern.svg") { let insets = EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10) context.draw(svg, in: CGRect(origin: .zero, size: size), capInsets: insets, byTiling: true) } } ``` ``` -------------------------------- ### 9-Slice Drawing with Core Graphics Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/quick-start.md Implement 9-slice drawing for scalable UI elements like buttons. Define custom insets to control how the SVG is sliced and stretched. ```swift let buttonSVG = SVG(named: "button-bg.svg")! let insets = (top: 20.0, left: 20.0, bottom: 20.0, right: 20.0) context.draw( buttonSVG, in: targetRect, capInsets: insets, byTiling: false // stretch mode ) ``` -------------------------------- ### Convert SVG to PDF using Command Line Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/quick-start.md Convert an SVG file to PDF format using the SwiftDraw command-line tool. This is useful for generating vector-based documents. ```bash swiftdraw document.svg --format pdf ``` -------------------------------- ### Create NSImage from SVG Name Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/nsimage-extensions.md Use this initializer to create an NSImage from an SVG resource located within a bundle. Specify the SVG's name and optionally the bundle and parsing options. ```swift public convenience init?(svgNamed name: String, in bundle: Bundle = .main, options: SVG.Options = .default) ``` ```swift import AppKit import SwiftDraw let image = NSImage(svgNamed: "icon.svg") imageView.image = image ``` -------------------------------- ### draw(_:in:capInsets:byTiling:) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/api-reference/cgcontext-extensions.md Draw an SVG using 9-slice (cap insets) drawing. This method divides the SVG into 9 regions for flexible scaling and tiling. ```APIDOC ## draw(_:in:capInsets:byTiling:) ### Description Draw an SVG using 9-slice (cap insets) drawing. The SVG is divided into 9 regions: 4 corners, 4 edges, and a center. Corners are never scaled; edges and center scale or tile as specified. ### Method `public func draw( _ svg: SVG, in rect: CGRect, capInsets: (top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat), byTiling: Bool )` ### Parameters #### Path Parameters - **svg** (`SVG`) - Required - SVG to draw - **rect** (`CGRect`) - Required - Target rectangle - **capInsets** (tuple) - Required - Inset distances (top, left, bottom, right) from SVG edges - **byTiling** (`Bool`) - Required - Whether to tile or stretch edge and center regions ### Request Example ```swift let svg = SVG(named: "button.svg")! // Draw with 30pt insets on all sides, stretching content let insets = (top: 30.0, left: 30.0, bottom: 30.0, right: 30.0) context.draw( svg, in: targetRect, capInsets: insets, byTiling: false ) ``` ### Response Void ``` -------------------------------- ### Specify Absolute or Relative File Path Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Use absolute or relative paths to specify input files for Swiftdraw. This helps resolve 'File not found' errors. ```bash swiftdraw /absolute/path/to/icon.svg ``` ```bash swiftdraw ./relative/icon.svg ``` -------------------------------- ### Generate Swift Code (UIKit) Source: https://github.com/swhitty/swiftdraw/blob/main/_autodocs/command-line-reference.md Generate UIKit code for an icon from an SVG file. This uses UIGraphics-based rendering. ```bash swiftdraw icon.svg --format swift --api uikit --output Icon.swift ```