Skip to content

Instantly share code, notes, and snippets.

@msanders
Created March 3, 2017 19:22
Show Gist options
  • Save msanders/90658c429c68e492055b82343a178065 to your computer and use it in GitHub Desktop.
Save msanders/90658c429c68e492055b82343a178065 to your computer and use it in GitHub Desktop.
import UIKit
extension UIImage {
convenience init?(uncachedName name: String) {
let deviceScale: Double = Double(UIScreen.mainScreen().scale)
let scaleFactors = [1.0, 2.0, 3.0].sort { x, y -> Bool in
let distanceA = abs(x - deviceScale)
let distanceB = abs(y - deviceScale)
return distanceA == distanceB ? x > y : distanceA < distanceB
}
for scale in scaleFactors {
let suffix = String(format: "@%.fx", scale)
let bundle = NSBundle.mainBundle()
let resource: String = "\(name)\(suffix)"
let pathExtension: String = (name as NSString).pathExtension
if let path = bundle.pathForResource(resource, ofType: pathExtension.isEmpty ? "png" : pathExtension) {
self.init(contentsOfFile: path)
return
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment