我最终只是为每个设备创建了一个不同的文件,并将它们命名为imageName@size
,因此对于狗的图像128x128
,文件将命名为dog@128
.
这是我用来执行此操作的代码
func getPNGImageForSize(size: Float, named: String) -> UIImage?{
//the image size will be measured in points, which is the unit that is used
//when setting the frames of UIViews. To turn this into pixels, it must be
//multiplied by the screen's render scale (on an iPhone 6+, 1 point is equal
//to 3 pixels, or 9 pixels in 2 dimensions (3^2).
let scaled: Int = Int(ceil(size * Float(UIScreen.mainScreen().scale))
let imageName: String = "\(named)@\(scaled)"
//ofType set to png, because this image is a PNG
let path = NSBundle.mainBundle().pathForResource(imageName, ofType: "png")
return UIImage(contentsOfFile: (path ?? ""))
}
要调用它,我只需使用
getPNGImageForSize(Float(self.view.frame.height / 4), named: "dog")
这将导致以下图像,具体取决于设备
iPhone 4s 狗@240.png
iPhone 5/5s dog@284.png
iPhone 6 狗@334.png
iPhone 6+ dog@480.png
这也可以更改为使用非方形图像,命名为imageName@width-height
func getPNGImageForSize(width: Float, height: Float, named: String) -> UIImage?{
let scaledWidth: Int = Int(ceil(width * Float(UIScreen.mainScreen().scale))
let scaledHeight: Int = Int(ceil(height * Float(UIScreen.mainScreen().scale))
let imageName: String = "\(named)@\(width)-\(height)"
let path = NSBundle.mainBundle().pathForResource(imageName, ofType: "png")
return UIImage(contentsOfFile: (path ?? ""))
}