Accessing an image with specific resolution in the

2019-02-25 04:14发布

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条回答
地球回转人心会变
2楼-- · 2019-02-25 04:26

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]))
查看更多
登录 后发表回答