Sti
Sti

Reputation: 8493

How to resize UIImage vector graphic

This is a rather strange question. You're probably thinking "You must resize the UIImageView, not the UIImage", but I can't get it working, and I'm not sure it's correct in this case.

I have a .pdf vector image I want to use in an iOS application. This vector image was exported to .pdf with the default size of 320 width. Of course, this is vector, so it should scale perfectly.

When I create an UIImageView using that image (UIImageView(image: vectorImage)) it always gets a width of 320 (or scaled @2x/@3x).

I have constrained the UIImageView to have margin 0 left and right. On iPhone 5, this displays correctly, since it's a 320-based size screen. However, on iPhone 6 - the resolution is different, with a 375-based screen width. Even though the imageView is constrained to the full width (375), the UIImage within still has a size of 320. I never set the height. To clarify, I'm using ScaleAspectFit. This should not cause the image to be stuck at 320 though. As I never set the height of the UIImageView, it should begin with a correct fit.

I can probably solve this if I have the aspect ratio for the image, but that seems unnecessary!

A correct result would be for the image to fill the entire width of the imageView, and the height of the imageView to change to fit the image. The actual result is that the height and width of the UIImage is the same for all devices (relatively), and the height for the UIImageView is the same for all devices. Due to the constraints added, the width of the UIImageView is different, but the UIImage within is not changed. Why not? I suspect that if the vector-image had been exported with a different default size, the result would be different. Why is this?

Upvotes: 1

Views: 1820

Answers (1)

Leon
Leon

Reputation: 3746

This post gets a lot of views so maybe worth a quick answer in case it helps anyone.

When using vectors you can't set the image and to the UIImageView and expect it to work out its height from the width, even when setting it to ScaleAspectFit.

One way to resolve this is to get the UIImage, get it's size and then use this to set the UIImageView height constraint.

For example:

let image = UIImage(named: "name")!
let ratio = image.size.height / image.size.width

imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: ratio).isActive = true

Upvotes: 1

Related Questions