Skip to content

Understanding MacawView content layout

Yuri Strot edited this page Jun 8, 2018 · 5 revisions

Note: this document describes features which available since 0.9.2.

Content Mode

Most of SVG files have some fixed size defined with width and height properties:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="..."
     width="500" height="500" viewBox="...">
...
</svg>

Let's say we're loading such a file and showing it in MacawView:

let logo = try! SVGParser.parse(path: "macaw-logo")
let view = MacawView(node: logo, frame: UIScreen.main.bounds)
view.backgroundColor = UIColor.white
self.view.addSubview(view)

By default, MacawView just directly map SVG coordinate system into device system. So if we're showing 500x500 SVG file it will look like this:

Fortunately we can use contentMode property to better fit our needs. Let's add the following line to our sample:

view.contentMode = .scaleAspectFit

And that's how it looks after this change:

With content mode Macaw automatically updates display when view bounds will be changed:

scaleAspectFit looks like reasonable default value, however it was only implemented in 0.9.2 version and to keep backward compatibility Macaw just map one coordinate system to another by default.

Content Layout

There is also contentLayout property and you can use it to create your own automatic layouts.

First, we need to create a class which extends ContentLayout. Let's create a funny layout which works like scaleToFill, but also rotate SVG upside down:

class MyLayout: ContentLayout {

    override func layout(rect: Rect, into sizeToFitIn: Size) -> Transform {
        // scale scene to fit view bounds
        return Transform.scale(sx: sizeToFitIn.w / rect.w, sy: sizeToFitIn.h / rect.h)
            // rotate scene upside down around the center
            .rotate(angle: .pi, x: rect.center().x, y: rect.center().y)
    }
}

Finally, just set this layout to our view using contentLayout property:

view.contentLayout = MyLayout()

And here we are:

SVG Layout

Some SVG files don't have fixed size. Instead they support flexible size and define own layout using preserveAspectRatio attribute. Such SVG files set width/height to 100% or avoid them (100% is default value for width/height properties).

In this case MacawView ignores contentMode/contentLayout and uses layout defined in the SVG file.

Clone this wiki locally