Created
March 28, 2016 14:57
-
-
Save lvterry/f062cf9ae13bca76b0c6 to your computer and use it in GitHub Desktop.
Convert PHAsset to UIImage with Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// it returns a square thumbnail. | |
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage { | |
let retinaScale = UIScreen.mainScreen().scale | |
let retinaSquare = CGSizeMake(size * retinaScale, size * retinaScale) | |
let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight) | |
let square = CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength)) | |
let cropRect = CGRectApplyAffineTransform(square, CGAffineTransformMakeScale(1.0/CGFloat(asset.pixelWidth), 1.0/CGFloat(asset.pixelHeight))) | |
let manager = PHImageManager.defaultManager() | |
let options = PHImageRequestOptions() | |
var thumbnail = UIImage() | |
options.synchronous = true | |
options.deliveryMode = .HighQualityFormat | |
options.resizeMode = .Exact | |
options.normalizedCropRect = cropRect | |
manager.requestImageForAsset(asset, targetSize: retinaSquare, contentMode: .AspectFit, options: options, resultHandler: {(result, info)->Void in | |
thumbnail = result! | |
}) | |
return thumbnail | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 5