Access to an image with a specific resolution in the Asset Catalog

I have a set of images called "SmileyFace" which contains 1x, 2x and 3x image sizes. I want to copy to copy a specific size from a set of images. How do I refer to the 1x, 2x, or 3x code in the code below?

let image = UIImage(named: "SmileyFace" )
let image2 = UIImagePNGRepresentation( image )
UIPasteboard.generalPasteboard().setData(image2, forPasteboardType: "public.png")

      

This code copies 1x. I want to copy a 2x image.

I haven't found anything in the Apple Documentation that seems to link to this.

+3


source to share


1 answer


You can use the method imageAsset.registerImage()

:

  let scale1x = UITraitCollection(displayScale: 1.0)
  let scale2x = UITraitCollection(displayScale: 2.0)
  let scale3x = UITraitCollection(displayScale: 3.0)

  let image = UIImage(named: "img.png")!
  image.imageAsset.registerImage(UIImage(named: "img_2x.png")!, withTraitCollection: scale2x)
  image.imageAsset.registerImage(UIImage(named: "img_3x.png")!, withTraitCollection: scale3x)

      

You can register 2x image for all scales.



However, I don't think it's a good idea to access the image at a specific resolution. The idea is if a set of 1x, 2x and 3x images is to let the system decide which image should be loaded. If you really want to, you can change the name of your 1x, 2x and 3x images to SmileyFace-Small, SmileyFace-regular, SmileyFace-large.

UPDATE: func imageWithTraitCollection(traitCollection: UITraitCollection) -> UIImage

can reference an image with a specific scale:

  let image1 = image.imageAsset.imageWithTraitCollection(UITraitCollection(traitsFromCollections: [scale1x]))
  let image2 = image.imageAsset.imageWithTraitCollection(UITraitCollection(traitsFromCollections: [scale2x]))
  let image3 = image.imageAsset.imageWithTraitCollection(UITraitCollection(traitsFromCollections: [scale3x]))

      

+3


source







All Articles