Skip to content

Instantly share code, notes, and snippets.

@matsuda
Created March 8, 2019 11:33
Show Gist options
  • Save matsuda/8e24252ec79fdbb2554cfaf525df3159 to your computer and use it in GitHub Desktop.
Save matsuda/8e24252ec79fdbb2554cfaf525df3159 to your computer and use it in GitHub Desktop.
Utility for UIImage
public extension UIImage {
/// 画像を指定したサイズでリサイズする
/// @see https://qiita.com/ruwatana/items/473c1fb6fc889215fca3
func resized(to size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
draw(in: CGRect(origin: .zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/// 画像を指定したサイズで上部から切り抜く
/// @see https://qiita.com/takabosoft/items/391b7593f0b9ef7d77a5
func cropped(to size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
draw(at: CGPoint(x: 0, y: 0))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
private var opaque: Bool {
if let cgImage = cgImage {
switch cgImage.alphaInfo {
case .noneSkipLast, .noneSkipFirst:
return true
default:
break
}
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment