SVGKit: scaling SVG images

This is very easy, but lots of people find this difficult with good reason!

Here’s a quick guide to how image-scaling is implemented with SVGKit, so you can effortlessly scale your images.

REQUIRED

For any of these techniques to work, we need to know the size of your incoming SVG. According to the spec, EVERY SVG file is supposed to have a size, but it is POSSIBLE for an SVG to be saved “without a size”.

This is rare, but it does happen.

In that specific case, we CANNOT do some of the things below (the exception is “scale” — we can do this, using a one-liner built-in to SVGKit, but it would be safer for you to fix your SVG file!).

In particular, we definitely CANNOT scale to fit – because your SVG is infinite. You need to edit the SVG file and set the “width” attribute on the root <svg> tag, or you need to set the “viewBox” attribute (on the same tag).

Use 1: Scale-to-fit

All you have to do is provide a specific size for your SVGKImage, after it’s finished parsing. It will do the rest for you automatically:

[objc]
SVGKImage im = [SVGKImage imageNamed:"myImage"];
im.size = CGSizeMake( 320, 480 ); // fill an iOS screen
SVGKImageView* iv = [[SVGKFastImageView alloc] initWithSVGKImage: im];

[self.view addSubview: iv];
[/objc]

Use 2: Make it half the size

In this case, you need to specify a size “half as big as the default”.

All you have to do is provide a specific size for your SVGKImage, after it’s finished parsing. It will do the rest for you automatically:

[objc]
SVGKImage im = [SVGKImage imageNamed:"myImage"];
CGSize originalSize = im.size; // this defaults to the SVG’s internal size
float half = 1.0 / 2.0f;
im.size = CGSizeApplyAffineTransform( im.size, CGAffineTransformMakeScale( half, half ));
SVGKImageView* iv = [[SVGKFastImageView alloc] initWithSVGKImage: im];

[self.view addSubview: iv];
[/objc]

Use 3: Make it half the size – when the SVG is infinite

If the SVG is infinite, we can’t make the image half as big – but we can RENDER it half as big. In this case, it’ll be up to you to “guesstimate” what .frame to place on the SVGKImageView at the end – or set it to the biggest size you care about rendering?

[objc]
SVGKImage im = [SVGKImage imageNamed:"myImage"];
im.scale = 0.5f; // NB: this will BE REJECTED if your SVG is non-infinite;
// … use the other techniques (listed above) instead!
SVGKImageView* iv = [[SVGKFastImageView alloc] initWithSVGKImage: im];

[self.view addSubview: iv];
[/objc]

Leave a Reply

Your email address will not be published. Required fields are marked *