Search Docs
Loading...
Skip to content

Import SVG as Editable Shapes

Turn SVG markup into editable shapes that keep their paths, colors, gradients and strokes.

6 mins
estimated time
GitHub

engine.block.createFromSVG(_:) reads SVG markup, such as the content of an SVG file or the SVG code that Adobe Illustrator copies to the clipboard, and creates graphic blocks from it. You can then change the fill and stroke of each shape. To place an SVG file as one flat image instead, see Insert Images.

This guide covers what the import creates, how to add the result to a page and fit it, how SVG units map to the scene’s design unit, how to edit the imported shapes, and how to handle import errors.

Importing the SVG Markup#

The sample starts with SVG markup for a badge: a circle with a radial gradient, a star with a stroke, and a dashed line. In an app, this string comes from a file the user picks or from the clipboard.

// A badge with a radial gradient, a stroked star and a dashed line.
let badgeSVG = """
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 240 240">
<defs>
<radialGradient id="glow" cx="120" cy="120" r="110" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#ffd166"/>
<stop offset="1" stop-color="#ef476f"/>
</radialGradient>
</defs>
<circle cx="120" cy="120" r="110" fill="url(#glow)"/>
<polygon points="120,40 143,97 205,97 155,133 174,192 120,156 66,192 85,133 35,97 97,97"
fill="#ffffff" stroke="#073b4c" stroke-width="6" stroke-linejoin="round"/>
<path d="M60 212 H180" fill="none" stroke="#073b4c" stroke-width="4"
stroke-dasharray="12 6" stroke-linecap="round"/>
</svg>
"""

Pass the markup to engine.block.createFromSVG(_:). The created blocks have no parent, so append the returned block to the page with engine.block.appendChild(to:child:). Until then, the blocks are not visible.

let badge = try engine.block.createFromSVG(badgeSVG)
try engine.block.appendChild(to: page, child: badge)

Understanding What the Import Creates#

Each SVG shape (path, rect, circle, ellipse, line, polyline and polygon) becomes a graphic block with a vector_path shape. The block keeps the shape’s fill color or its linear or radial gradient, and its stroke with color, width, joins, caps and dashes. A shape with fill="none" gets its fill disabled and keeps its stroke.

When the SVG has one shape, the call returns that graphic block. When it has more, the call returns a group. The group holds the shapes in paint order, so the first child is the bottom-most shape.

let badgeType = try engine.block.getType(badge)
print(badgeType == DesignBlockType.group.rawValue) // true
let children = try engine.block.getChildren(badge)
for child in children {
let shape = try engine.block.getShape(child)
let shapeType = try engine.block.getType(shape)
print(shapeType == ShapeType.vectorPath.rawValue) // true
}

Mapping SVG Units to the Design Unit#

The import reads one SVG user unit as one pixel in a scene that uses pixels. In a scene that uses millimeters or inches, one user unit is one point (1/72 inch), as Adobe Illustrator writes it. An SVG whose width and height are given in mm or in keeps its physical size. Read the scene’s unit with engine.scene.getDesignUnit(). See Design Units to change it.

let usesPixels = try engine.scene.getDesignUnit() == .px
print(usesPixels) // true

Fitting the Design on the Page#

The position and size of the returned block are readable right after the import. The sample computes a factor that makes the badge fill 80% of the page, and applies it with engine.block.scale(_:to:anchorX:anchorY:). This call also scales the children and their stroke widths and dashes, so the design keeps its proportions. Then it centers the block with engine.block.setPositionX(_:value:) and engine.block.setPositionY(_:value:).

let pageWidth = try engine.block.getWidth(page)
let pageHeight = try engine.block.getHeight(page)
let factor = try 0.8 * min(
pageWidth / engine.block.getWidth(badge),
pageHeight / engine.block.getHeight(badge),
)
// scale(_:to:anchorX:anchorY:) also scales the stroke widths and dashes.
try engine.block.scale(badge, to: factor)
try engine.block.setPositionX(badge, value: (pageWidth - engine.block.getWidth(badge)) / 2)
try engine.block.setPositionY(badge, value: (pageHeight - engine.block.getHeight(badge)) / 2)

Editing the Imported Shapes#

The imported shapes are ordinary graphic blocks. The sample changes the star’s fill color with engine.block.getFill(_:) and engine.block.setColor(_:property:color:), and makes the dashed line thicker with engine.block.setStrokeWidth(_:width:).

let star = children[1]
let line = children[2]
let starFill = try engine.block.getFill(star)
try engine.block.setColor(
starFill,
property: "fill/color/value",
color: .rgba(r: 0.02, g: 0.84, b: 0.63, a: 1),
)
try engine.block.setStrokeWidth(line, width: 12)

To work with the shapes as separate blocks, dissolve the group with engine.block.ungroup(_:). See Grouping.

Handling Import Errors#

When the import fails, the call throws an EngineError and creates no block. Branch on its catalogCode, which is an EngineErrorCode:

  • BLOCK.SVG_NOT_READABLE (.blockSvgNotReadable): the markup has no <svg> root element.
  • BLOCK.SVG_EMPTY (.blockSvgEmpty): the SVG has no size, or draws nothing inside its viewport.
  • BLOCK.SVG_TOO_MANY_PARTS (.blockSvgTooManyParts): the SVG has more than 5000 parts.
  • BLOCK.SVG_PART_NOT_RENDERED (.blockSvgPartNotRendered): the device had too little memory to draw a part without a shape as an image.
do {
let block = try engine.block.createFromSVG("<html><body>No SVG here</body></html>")
try engine.block.appendChild(to: page, child: block)
} catch let error as EngineError where error.catalogCode == .blockSvgNotReadable {
print("The markup has no SVG root element: \(error.localizedDescription)")
}

Troubleshooting#

  • The import succeeds but nothing appears: the created blocks have no parent. Append the returned block to a page with engine.block.appendChild(to:child:).
  • The design is much larger or smaller than expected: check the scene’s design unit. The same SVG has a different size in a pixel scene and in a millimeter scene. Fit the block to the page with engine.block.scale(_:to:anchorX:anchorY:) after the import.
  • Some parts cannot be edited as paths: text, embedded images, filters, masks and patterns become image fills. Recreate text with a text block if users must edit it.
  • Text in the SVG is missing or draws in another font: the import turns each text into an image at once, with the fonts that are loaded at that moment. Text draws in a font of its family when the scene or a font asset source has one and that font is already loaded, and in the default font otherwise. Text that needs the default font is left out for good when the default font is not loaded yet. Emoji and other characters that need a fallback font draw as the missing-character mark when that fallback font is not loaded yet, because the import does not wait for it. Convert the text to outlines before you export the SVG, so that the import shows it in every case.
  • The import fails with an SVG that has content (.blockSvgEmpty): give the SVG a viewBox, or a width and height, and check that its shapes are inside the viewport.
  • A large illustration fails to import (.blockSvgTooManyParts): merge shapes of one color into compound paths in the design tool, or add the SVG as an image.

API Reference#

Methods#

Method Description
engine.block.createFromSVG(_:) Create editable graphic blocks from SVG markup. Returns the group, or the only block
engine.block.appendChild(to:child:) Add the imported block to a page
engine.block.getType(_:) Tell a group from a single graphic block
engine.block.getChildren(_:) List the shapes of the group in paint order
engine.block.getShape(_:) Read the vector_path shape of an imported block
engine.block.getWidth(_:) / getHeight(_:) Read the size of the imported block and the page
engine.block.scale(_:to:anchorX:anchorY:) Scale a block, its children and their strokes
engine.block.setPositionX(_:value:) / setPositionY(_:value:) Center the block on the page
engine.block.getFill(_:) Read the fill of an imported shape
engine.block.setColor(_:property:color:) Change a fill color
engine.block.setStrokeWidth(_:width:) Change a stroke width
engine.block.ungroup(_:) Dissolve the group into separate blocks
engine.scene.getDesignUnit() Read the unit that SVG user units map to
EngineError.catalogCode Read the error code of a failed import

Next Steps#