A Swift library for parsing and drawing SVG images to CoreGraphics contexts.

Related tags

Image SwiftDraw
Overview

CodeCov License Twitter

SwiftDraw

A Swift library for parsing and drawing SVG images to CoreGraphics contexts. SwiftDraw can also convert an SVG into Swift source code.

Usage

iOS

import SwiftDraw
let image = UIImage(svgNamed: "sample.svg")

macOS

import SwiftDraw
let image = NSImage(svgNamed: "sample.svg")

Command line tool

Download the latest command line tool here.

$ swiftdraw sample.svg --format pdf --size 48x48

Source code generation

The command line tool can also convert an SVG image into Swift source code:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="160" height="160">
  <rect width="160" height="160" fill="snow" />
  <path d="m 80 20 a 50 50 0 1 0 50 50 h -50 z" fill="pink" stroke="black" stroke-width="2"/>
</svg>

$ swiftdraw simple.svg --format swift

extension UIImage {
  static func svgSimple() -> UIImage {
    let f = UIGraphicsImageRendererFormat.default()
    f.opaque = false
    f.preferredRange = .standard
    return UIGraphicsImageRenderer(size: CGSize(width: 160.0, height: 160.0), format: f).image {
      drawSVG(in: $0.cgContext)
    }
  }

  private static func drawSVG(in ctx: CGContext) {
    let rgb = CGColorSpaceCreateDeviceRGB()
    let color1 = CGColor(colorSpace: rgb, components: [1.0, 0.98039216, 0.98039216, 1.0])!
    ctx.setFillColor(color1)
    let path = CGPath(
      roundedRect: CGRect(x: 0.0, y: 0.0, width: 160.0, height: 160.0),
      cornerWidth: 0.0,
      cornerHeight: 0.0,
      transform: nil
    )
    ctx.addPath(path)
    ctx.fillPath(using: .evenOdd)
    let color2 = CGColor(colorSpace: rgb, components: [1.0, 0.7529412, 0.79607844, 1.0])!
    ctx.setFillColor(color2)
    let path1 = CGMutablePath()
    path1.move(to: CGPoint(x: 80.0, y: 20.0))
    path1.addCurve(to: CGPoint(x: 30.0, y: 69.99999),
                   control1: CGPoint(x: 52.38576, y: 20.0),
                   control2: CGPoint(x: 30.000004, y: 42.385757))
    path1.addCurve(to: CGPoint(x: 79.99998, y: 120.0),
                   control1: CGPoint(x: 29.999992, y: 97.61423),
                   control2: CGPoint(x: 52.385742, y: 119.999985))
    path1.addCurve(to: CGPoint(x: 130.0, y: 70.00004),
                   control1: CGPoint(x: 107.61421, y: 120.000015),
                   control2: CGPoint(x: 129.99998, y: 97.61427))
    path1.addLine(to: CGPoint(x: 80.0, y: 70.00004))
    path1.closeSubpath()
    ctx.addPath(path1)
    ctx.fillPath(using: .evenOdd)
    ctx.setLineCap(.butt)
    ctx.setLineJoin(.miter)
    ctx.setLineWidth(2.0)
    ctx.setMiterLimit(4.0)
    let color3 = CGColor(colorSpace: rgb, components: [0.0, 0.0, 0.0, 1.0])!
    ctx.setStrokeColor(color3)
    ctx.addPath(path1)
    ctx.strokePath()
  }
}
Comments
  • Parsing error missingAttribute(name:

    Parsing error missingAttribute(name: "offset")

    Microsoft has released a huge Emoji set as open source. https://github.com/microsoft/fluentui-emoji

    For each Emoji, three SVG files "Color", "Flat", and "High Contrast" and a PNG image "3D" are available. SwiftDraw seems to fail to convert most SVGs of type "Color". The error messages are all parsing error missingAttribute(name: "offset").

    Try face_with_open_mouth_color.svg.

    $ swiftdraw face_with_open_mouth_color.svg --format png --size 512x512
    [swiftdraw] parsing error missingAttribute(name: "offset")
    Failure
    

    The only "Flat" type that fails to convert is eleven_oclock_flat.svg.

    $ swiftdraw eleven_oclock_flat.svg --format png --size 512x512
    [swiftdraw] parsing error missingAttribute(name: "offset")
    Failure
    

    In addition, a few of the "Color" types are successfully converted, but most of them are not converted correctly. For example, the conversion of avocado_color.svg results in a black cross section. (This may be a separate issue from the above.)

    swiftdraw_avocado

    I'm not sure if you plan to support such complex SVGs, but I'm reporting this just in case.

    opened by 2n 14
  • Is there an easy way to override fill color?

    Is there an easy way to override fill color?

    Like with https://github.com/mchoe/SwiftSVG you can do:

    let svgURL = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
    let hammock = UIView(SVGURL: svgURL) { (svgLayer) in
        svgLayer.fillColor = UIColor(red:0.52, green:0.16, blue:0.32, alpha:1.00).cgColor
        svgLayer.resizeToFit(self.view.bounds)
    }
    self.view.addSubview(hammock)
    

    thanks.

    opened by eonist 10
  • Internal stylesheet support?

    Internal stylesheet support?

    At the moment SwiftDraw only seems to support style attributes that are set directly on SVG elements. Many tools create SVG files with an embedded stylesheet and rely on the style cascade to apply them to the elements. I can imagine this would be a significant undertaking, but it would be a great compatibility improvement if both types of files could be rendered.

    For instance, here are two 'identical' SVGs that differ only in terms of where their styles live:

    inline styles

    inline

    internal stylesheet

    internal

    SwiftDraw produces very different output when rendering them though: image

    opened by samizdatco 4
  • Usable from Objective-C?

    Usable from Objective-C?

    Thanks so much for this terrific library. I've been looking into getting it working with an old objc-based app of mine and am a little confused by the interface in the generated headers. I can see in Image.swift that the init method can handle urls, bundle names, as well as data. But the SwiftDraw-Swift.h file that's generated via swift build only contains argument-less stubs:

    SWIFT_CLASS_NAMED("Image")
    @interface SVGImage : NSObject
    - (nonnull instancetype)init SWIFT_UNAVAILABLE;
    + (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable");
    @end
    

    Shouldn't the various other initializers also be present (or am I missing something obvious here)?

    opened by samizdatco 4
  • Svg image seems to be blurry and doesn't parse some part properly when imageView frame is small

    Svg image seems to be blurry and doesn't parse some part properly when imageView frame is small

    It seems that svg image is blurry & doesn't parse some part properly (take a look at "BET" in the beginning) if the image size is less than imageView size. It did not look ideally in previous versions but in 0.13.0 it looks really bad.

    I tested on iPhone 11 IOS 15.6

    IMG_1117

    I also attached sample project and .svg image. SVG.zip logo

    opened by Dmitry-Pliushchai 3
  • MacCatalyst support

    MacCatalyst support

    Getting this error and others, related to Mac Catalyst support.

    SwiftDraw/SwiftDraw/NSImage+Image.swift:67:29: error build: 'NSGraphicsContext' is unavailable in Mac Catalyst
    
    Screen Shot 2022-10-07 at 3 36 57 PM
    opened by FullQueueDeveloper 2
  • Some RadialGradient is not drawn

    Some RadialGradient is not drawn

    Sorry to bother you again.

    It seems to be drawn when both stop-color and stop-opacity are inside the <stop> tag, but not when only stop-opacity is present.

    The following RadialGradient is drawn,

    <radialGradient id="paint6_radial_31_1432" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(20.5 18) rotate(9.86581) scale(11.6726)">
    <stop stop-color="#FFA64B"/>
    <stop offset="0.900412" stop-color="#FFAE46" stop-opacity="0"/>
    </radialGradient>
    

    but the following is not drawn.

    <radialGradient id="paint7_radial_31_1432" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(17.5 15) rotate(43.9708) scale(59.0529)">
    <stop offset="0.185425" stop-opacity="0"/>
    <stop offset="1" stop-opacity="0.4"/>
    </radialGradient>
    

    I noticed this because angry_face_color.svg had subtle differences from the originals, even though they did not contain unsupported tags.

    This is based on my poor research and I apologize if I am wrong.

    opened by 2n 2
  • Strange line breakage

    Strange line breakage

    This library helps me every day. Thank you so much.

    I have tried to convert Feather icons using version 0.9.5. Almost everything was converted correctly, but I could see a strange line breakage in "key.svg". swiftdraw_key

    I'm not sure if the problem is with the file or the library, but at least this SVG file shows up correctly in the macOS Finder and other graphics tools.

    The link to key.svg is here. https://feathericons.com/?query=key

    opened by 2n 2
  • Failed to convert Feather icons

    Failed to convert Feather icons

    Thank you for developing this wonderfully useful library. This library works very well, but fails to convert Feather icons.

    I downloaded several icons from the links below and tried to convert them with the latest version of the command line tool, but all failed. https://feathericons.com

    $ swiftdraw home.svg --format swift
    Failure
    

    This is my first time posting on Issues so I apologize if I am rude.

    opened by anodetamer 2
  • Issue #12 - UIGraphicsImageRenderer should applying scaling

    Issue #12 - UIGraphicsImageRenderer should applying scaling

    0.13.0 introduced a regression where images rasterized to UIImage would be scaled twice.

    UIGraphicsImageRenderer should apply scale and image should be sized in points (scale 1)

    https://github.com/swhitty/SwiftDraw/issues/12

    opened by swhitty 1
  • error build: Entry point (_main) undefined. for architecture x86_64

    error build: Entry point (_main) undefined. for architecture x86_64

    I have two error the first is in the title and second one is: "/Users/alexanderruder/Library/Developer/Xcode/DerivedData/W4U-Risikoapp-avswhmmknksifadrneimtyrnozkq/SourcePackages/checkouts/SwiftDraw/SwiftDraw/Parser.XML.StyleSheet.swift:167:16: error build: Cannot find type 'SwiftDraw' in scope

    Thanks in advance

    opened by Azilla030 3
Releases(0.13.3)
  • 0.13.3(Jan 3, 2023)

    Adds optional --output to Command-line tool. If provided this path is used, otherwise a suffix is automatically appended to input path.

    Fixes bugs

    • UIImage was scaled twice https://github.com/swhitty/SwiftDraw/issues/12.
    • fill-rule was defaulting to evenodd when it should be nonzero
    • macCatalyst support
    • Better support for stroke gradients https://github.com/swhitty/SwiftDraw/issues/17
    swiftdraw, version 0.13.2
    copyright (c) 2022 Simon Whitty
    
    usage: swiftdraw <file.svg> [--format png | pdf | jpeg | swift | sfsymbol] [--size wxh] [--scale 1x | 2x | 3x]
    
    <file> svg file to be processed
    
    Options:
     --format      format to output image: png | pdf | jpeg | swift | sfsymbol
     --size        size of output image: 100x200
     --scale       scale of output image: 1x | 2x | 3x
     --insets      crop inset of output image: top,left,bottom,right
     --precision   maximum number of decimal places
     --output      optional path of output file
    
     --hideUnsupportedFilters   hide elements with unsupported filters.
    
    Available keys for --format swift:
     --api                api of generated code:  appkit | uikit
    
    Available keys for --format sfymbol:
     --insets             alignment of regular variant: top,left,bottom,right | auto
     --ultralight         svg file of ultralight variant
     --ultralightInsets   alignment of ultralight variant: top,left,bottom,right | auto
     --black              svg file of black variant
     --blackInsets        alignment of black variant: top,left,bottom,right | auto
    
    Source code(tar.gz)
    Source code(zip)
  • 0.13.2(Oct 7, 2022)

    Adds optional --output to Command-line tool. If provided this path is used, otherwise a suffix is automatically appended to input path.

    Fixes bugs

    • UIImage was scaled twice https://github.com/swhitty/SwiftDraw/issues/12.
    • fill-rule was defaulting to evenodd when it should be nonzero
    • macCatalyst support
    swiftdraw, version 0.13.2
    copyright (c) 2022 Simon Whitty
    
    usage: swiftdraw <file.svg> [--format png | pdf | jpeg | swift | sfsymbol] [--size wxh] [--scale 1x | 2x | 3x]
    
    <file> svg file to be processed
    
    Options:
     --format      format to output image: png | pdf | jpeg | swift | sfsymbol
     --size        size of output image: 100x200
     --scale       scale of output image: 1x | 2x | 3x
     --insets      crop inset of output image: top,left,bottom,right
     --precision   maximum number of decimal places
     --output      optional path of output file
    
     --hideUnsupportedFilters   hide elements with unsupported filters.
    
    Available keys for --format swift:
     --api                api of generated code:  appkit | uikit
    
    Available keys for --format sfymbol:
     --insets             alignment of regular variant: top,left,bottom,right | auto
     --ultralight         svg file of ultralight variant
     --ultralightInsets   alignment of ultralight variant: top,left,bottom,right | auto
     --black              svg file of black variant
     --blackInsets        alignment of black variant: top,left,bottom,right | auto
    
    Source code(tar.gz)
    Source code(zip)
    SwiftDraw.dmg(868.68 KB)
  • 0.13.1(Aug 31, 2022)

    Adds optional --output to Command-line tool. If provided this path is used, otherwise a suffix is automatically appended to input path.

    Fixes bugs

    • UIImage was scaled twice https://github.com/swhitty/SwiftDraw/issues/12.
    • fill-rule was defaulting to evenodd when it should be nonzero
    swiftdraw, version 0.13.1
    copyright (c) 2022 Simon Whitty
    
    usage: swiftdraw <file.svg> [--format png | pdf | jpeg | swift | sfsymbol] [--size wxh] [--scale 1x | 2x | 3x]
    
    <file> svg file to be processed
    
    Options:
     --format      format to output image: png | pdf | jpeg | swift | sfsymbol
     --size        size of output image: 100x200
     --scale       scale of output image: 1x | 2x | 3x
     --insets      crop inset of output image: top,left,bottom,right
     --precision   maximum number of decimal places
     --output      optional path of output file
    
     --hideUnsupportedFilters   hide elements with unsupported filters.
    
    Available keys for --format swift:
     --api                api of generated code:  appkit | uikit
    
    Available keys for --format sfymbol:
     --insets             alignment of regular variant: top,left,bottom,right | auto
     --ultralight         svg file of ultralight variant
     --ultralightInsets   alignment of ultralight variant: top,left,bottom,right | auto
     --black              svg file of black variant
     --blackInsets        alignment of black variant: top,left,bottom,right | auto
    
    Source code(tar.gz)
    Source code(zip)
    SwiftDraw.dmg(859.68 KB)
  • 0.13.0(Aug 25, 2022)

    Renames SwiftDraw.Image -> SwiftDraw.SVG avoiding name collisions with SwiftUI.Image.

    Updates command line tool:

    • officially support SF Symbol creation using --format sfsymbol
    • add ability to crop or align images with --insets 10,0,0,10
    • adds AppKit support with --format swift --api appkit
    • fixes PDFs rendering with unsupported transparency
    copyright (c) 2022 Simon Whitty
    
    usage: swiftdraw <file.svg> [--format png | pdf | jpeg | swift | sfsymbol] [--size wxh] [--scale 1x | 2x | 3x]
    
    <file> svg file to be processed
    
    Options:
     --format      format to output image: png | pdf | jpeg | swift | sfsymbol
     --size        size of output image: 100x200
     --scale       scale of output image: 1x | 2x | 3x
     --insets      crop inset of output image: top,left,bottom,right
     --precision   maximum number of decimal places
    
     --hideUnsupportedFilters   hide elements with unsupported filters.
    
    Available keys for --format swift:
     --api                api of generated code:  appkit | uikit
    
    Available keys for --format sfymbol:
     --insets             alignment of regular variant: top,left,bottom,right | auto
     --ultralight         svg file of ultralight variant
     --ultralightInsets   alignment of ultralight variant: top,left,bottom,right | auto
     --black              svg file of black variant
     --blackInsets        alignment of black variant: top,left,bottom,right | auto
    
    Source code(tar.gz)
    Source code(zip)
    SwiftDraw.dmg(854.36 KB)
  • 0.12.0(Aug 21, 2022)

    SFSymbol

    Adds experimental sfsymbol support to command line tool. SVGs can be converted to SFSymbol template which can be imported directly into Xcode.

    $ swiftdraw alert_fill.svg --format sfsymbol
    

    SwiftDraw automatically expands strokes (on macOS) and winds subpaths using the non zero rule to create a compatible symbol template.

    Style Sheet

    Adds style sheet support for simple selectors: class, element and id.

    .s {
       stroke: darkgray;
       stroke-width: 5 /* asd */;
       fill-opacity: 0.3
    }
    
    #a {
       fill: yellow;
    }
    
    .b {
       fill: blue;
    }
    
    rect {
       fill: pink;
    }
    
    Source code(tar.gz)
    Source code(zip)
    SwiftDraw.dmg(840.28 KB)
  • 0.11.1(Aug 18, 2022)

  • 0.11.0(Aug 17, 2022)

    Adds ability to stroke a path with a radial gradient.

    Enhances error logging to ensure it is logged to stderr and includes details of erroneous SVG line / file where appropriate.

    Image.Options

    Adds Image.Options to provide a way for the client to control how the SVG is rendered.

    A single option is provided .hideUnsupportedFilters which hides any SVG element that includes an unsupported filter. This option is not enabled by default. Images with unsupported filters render without the filter but log to stderr with a platform specific hint pointing to the option;

    Warning: <feGaussianBlur> is not supported. Elements with this filter can be hidden with UIImage(svgNamed: "yawn.svg", options: .hideUnsupportedFilters)
    
    Warning: <feGaussianBlur> is not supported. Elements with this filter can be hidden with NSImage(svgNamed: "yawn.svg", options: .hideUnsupportedFilters)
    
    Warning: <feGaussianBlur> is not supported. Elements with this filter can be hidden with [--hideUnsupportedFilters]
    
    Source code(tar.gz)
    Source code(zip)
    SwiftDraw.dmg(755.66 KB)
  • 0.10.2(Aug 16, 2022)

  • 0.10.1(Aug 14, 2022)

  • 0.9.6(Aug 3, 2022)

  • 0.9.5(Jul 30, 2022)

  • 0.9.4(Jul 24, 2022)

    Adds convenience initialisers to platform images;

    UIImage(svgData: Data)
    UIImage(contentsOfSVGFile path: String)
    
    NSImage(svgData: Data)
    NSImage(contentsOfSVGFile path: String)
    

    And exports to Objective-C

    - (instancetype) initWithSVGData: (NSData *)
    - (instancetype) initWithContentsOfSVGFile: (NSString *)
    
    Source code(tar.gz)
    Source code(zip)
    SwiftDraw.dmg(692.91 KB)
  • 0.9.3(Jul 11, 2022)

  • 0.9.2(Jul 11, 2022)

  • 0.9.1(Mar 6, 2022)

  • 0.9.0(Jan 9, 2022)

  • 0.8.0(Jun 19, 2021)

  • 0.7.6(Jun 6, 2021)

  • 0.7.5(Jun 6, 2021)

  • 0.7.3(Jul 12, 2020)

  • 0.7.2(Jun 27, 2020)

  • 0.7.1(May 22, 2020)

  • 0.7.0(Jan 5, 2020)

  • 0.6.0(Jun 10, 2019)

  • 0.5.0(Mar 28, 2019)

  • 0.4.0(Feb 12, 2019)

  • 0.3.1(Dec 7, 2018)

  • 0.3(Dec 7, 2018)

  • 0.2.1(Nov 19, 2018)

Owner
Simon Whitty
Simon Whitty
A Fast and Complete Swift Drawing Library

FastDraw A Fast and Complete Swift Drawing Library Description FastDraw is a high performance and highly extensible Drawing Library that supports Appl

Collin Zhang 18 Nov 14, 2022
A simple, performant, and lightweight SVG parser

Key Features Parsing performance that meets or beats other popular SVG Frameworks A simple architecture, optimized for extension, flexibility and deve

Michael Choe 1.8k Dec 29, 2022
❄️ SVG in Swift

Snowflake ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut ma

Khoa 949 Dec 14, 2022
A simple, declarative, functional drawing framework, in Swift!

DePict - A simple, declarative, functional drawing framework. To produce a drawing, call the Draw function (just type Draw and let autocomplete do the

David Cairns 35 Sep 16, 2021
Cross-platform Swift library for parsing SVGPath strings

Introduction Installation Usage Credits Introduction SVGPath is an open-source parser for the SVG path syntax, making it easy to create CGPaths from t

Nick Lockwood 90 Dec 23, 2022
Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web

Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work

Wei Wang 20.9k Dec 30, 2022
A high-performance image library for downloading, caching, and processing images in Swift.

Features Asynchronous image downloader with priority queuing Advanced memory and database caching using YapDatabase (SQLite) Guarantee of only one ima

Yap Studios 72 Sep 19, 2022
Style Art library process images using COREML with a set of pre trained machine learning models and convert them to Art style.

StyleArt Style Art is a library that process images using COREML with a set of pre trained machine learning models and convert them to Art style. Prev

iLeaf Solutions Pvt. Ltd. 222 Dec 17, 2022
iOS library for quickly displaying images while scrolling

Fast Image Cache is an efficient, persistent, and—above all—fast way to store and retrieve images in your iOS application. Part of any good iOS applic

Path Mobile Inc Pte. Ltd. 8.2k Jan 9, 2023
ThreeDCardView - Library that you can see images with a 3D card 🌌

?? ThreeDCardView Usage First you have to import 'ThreeDCardView' import 'ThreeDCardView' Create ThreeDCardView and set the frame let threeDCardView:T

Fomagran 4 Jul 9, 2022
React-native-image-generator - Library to generate images from layers

react-native-image-generator Library for generate images from other images Insta

Evgeny Usov 13 Nov 16, 2022
FlaneurImagePicker is an iOS image picker that allows users to pick images from different sources (ex: user's library, user's camera, Instagram...). It's highly customizable.

FlaneurImagePicker is a highly customizable iOS image picker that allows users to pick images from different sources (ex: device's library, device's c

FlaneurApp 17 Feb 2, 2020
Media view which subclasses UIImageView, and can display & load images, videos, GIFs, and audio and from the web, and has functionality to minimize from fullscreen, as well as show GIF previews for videos.

I've built out the Swift version of this library! Screenshots Description ABMediaView can display images, videos, as well as now GIFs and Audio! It su

Andrew Boryk 80 Dec 20, 2022
APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS.

APNGKit is a high performance framework for loading and displaying APNG images in iOS and macOS. It's built on top of a modified version of libpng wit

Wei Wang 2.1k Dec 30, 2022
Image viewer (or Lightbox) with support for local and remote videos and images

Table of Contents Features Focus Browse Rotation Zoom tvOS Setup Installation License Author Features Focus Select an image to enter into lightbox mod

Nes 534 Jan 3, 2023
Jogendra 113 Nov 28, 2022
A Swift/SwiftUI utility for caching and displaying images in SwiftUI Views

A Swift/SwiftUI utility for caching and displaying images asynchronously. Built with Swift 5.5 and works with async/await.

王雪铮 Xuezheng Wang 1 May 5, 2022
Easily display images, animations, badges and alerts to your macOS application's dock icon

DSFDockTile Easily display images, animations, badges and alerts to your macOS application's dock icon. Why? I was inspired by Neil Sardesai after he

Darren Ford 45 Dec 2, 2022
Advanced framework for loading, caching, processing, displaying and preheating images.

Advanced framework for loading, caching, processing, displaying and preheating images. This framework is no longer maintained. Programming in Swift? C

Alexander Grebenyuk 1.2k Dec 23, 2022