Accessing an image with specific resolution in the Asset Catalog

僤鯓⒐⒋嵵緔 提交于 2019-12-20 02:55:09

问题


I have an Image Set called "SmileyFace" which contains a 1x, 2x and 3x image sizes. I want to copy to pasteboard a specific size from the image set. How do I reference the 1x, 2x or 3x programmatically in the code below?

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

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

I have not found anything in the Apple Documentation that seems to reference this.


回答1:


You can use imageAsset.registerImage() method:

  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 the scales.

However, I dont think it is good idea to access an image with specific resolution. The idea if 1x, 2x and 3x image set is to let the system to decide which image should be loaded. If you really want to, you might 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 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]))


来源:https://stackoverflow.com/questions/29804064/accessing-an-image-with-specific-resolution-in-the-asset-catalog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!