I thought the new Preserves Vector Data checkmark in the Xcode 9 asset catalog would finally give us resizing of vector PDF images, but apparently not. Here\'s my test image
It works, but only if you perform the resizing yourself:
That was achieved in code, like this:
let im = UIImage(named:"Image")!
let r = UIGraphicsImageRenderer(size:self.iv2.bounds.size)
let im2 = r.image {
_ in
im.draw(in: self.iv2.bounds)
}
self.iv2.image = im2
self.iv2.contentMode = .center
So UIImageView will rasterize as it scales (e.g. for Aspect Fit), but drawing in code will preserve the vector data.
EDIT New in Xcode 9 beta 5, this now works as expected! In this screen shot, the second image view just does a scale-to-fill, no more. We resize sharply!
EDIT In playing around with Xcode 11 I have finally found a formula that always works. This means that on launch, with no extra code, in an image view or elsewhere, a vector-based image appears sharp at any size.
In the asset catalog, you must set the Scales pop-up menu to Individual Scales and put the vector-based image into the 1x slot. Check Preserve Vector Data. Done.
In my case (Xcode 9.4.1), with imageView
created in Interface Builder - I noticed that when I initially arrive on the screen, the image is blurry. If I then change device orientation, the image becomes crisp. I tried calling different methods manually in viewDidLoad()
and here is what I found so far:
This worked:
let image = imageView.image
imageView.image = nil
imageView.image = image
None of these worked:
imageView.layoutSubviews()
imageView.layoutMarginsDidChange()
imageView.setNeedsLayout()
imageView.setNeedsDisplay()
imageView.reloadInputViews()
imageView.updateConstraints()
imageView.contentMode = .center ; imageView.contentMode = .scaleToFill
You should of course extend or subclass UIImageView
if you'll be calling it often, like this for example
class UIImageViewWithPreserveVectorDataFix: UIImageView {
override func awakeFromNib() {
super.awakeFromNib()
let image = self.image
self.image = nil
self.image = image
}
}
(and then of course set UIImageViewWithPreserveVectorDataFix
as the class in Interface Builder)
I had the same issue multiple times with the new Preserves Vector Data
.
Super simple solution that worked very well for me:
UIImageView
image
property in Interface Builder, just leave it empty.image
value programmatically.Hope it helps.
Edit: Still the same buggy behavior in Xcode 9 GM (9A235)
As of today (Xcode 9 beta 6 9M214v), the image will only be rendered properly (non-blurry) if the UIImageView has at least 3 spacing-related constraints.
eg. spacing to left, spacing to right, spacing to top, and another constraint to define the UIImageView height.
Note also that disabling autolayout completely will make all the UIImageView render incorrectly.
I filled rdar://34306192 (http://www.openradar.me/radar?id=4968083747766272) for this bug.