在资产目录中访问具有特定分辨率的图像 [英] Accessing an image with specific resolution in the Asset Catalog

查看:136
本文介绍了在资产目录中访问具有特定分辨率的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为SmileyFace的图像集,其中包含1x,2x和3x图像尺寸。我想从图像集中复制粘贴到特定大小的粘贴板。如何在下面的代码中以编程方式引用1x,2x或3x?

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")

此代码复制1x。我想要复制2x图像。

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

我在 Apple文档似乎引用了这一点。

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

推荐答案

您可以使用 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)

您可以为所有比例注册2x图像。

You can register 2x image for all the scales.

但是,我不认为访问具​​有特定分辨率的图像是个好主意。 1x,2x和3x图像集的想法是让系统决定应该加载哪个图像。如果您真的想要,可以将1x,2x和3x图像的名称更改为SmileyFace-Small,SmileyFace-regular,SmileyFace-large。

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.

更新:
func imageWithTraitCollection(traitCollection:UITraitCollection) - > UIImage 可以引用具有特定比例的图像:

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]))

这篇关于在资产目录中访问具有特定分辨率的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆