Skip to content

Instantly share code, notes, and snippets.

@uruly
Last active April 12, 2018 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uruly/d99e3ab484d19d5841e90da6175d57e9 to your computer and use it in GitHub Desktop.
Save uruly/d99e3ab484d19d5841e90da6175d57e9 to your computer and use it in GitHub Desktop.
extension UIImage {
func resize(size:CGSize) -> UIImage?{
// リサイズ処理
let origWidth = self.size.width
let origHeight = self.size.height
var resizeWidth:CGFloat = 0
var resizeHeight:CGFloat = 0
if (origWidth < origHeight) {
resizeWidth = size.width
resizeHeight = origHeight * resizeWidth / origWidth
} else {
resizeHeight = size.height
resizeWidth = origWidth * resizeHeight / origHeight
}
let resizeSize = CGSize(width:resizeWidth, height:resizeHeight)
UIGraphicsBeginImageContext(resizeSize)
self.draw(in: CGRect(x:0,y: 0,width: resizeWidth, height: resizeHeight))
let resizeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// 切り抜き処理
let cropRect = CGRect(x:( resizeWidth - size.width ) / 2,
y:( resizeHeight - size.height) / 2,
width:size.width,
height:size.height)
if let cropRef = resizeImage?.cgImage {
cropRef.cropping(to: cropRect)
let cropImage = UIImage(cgImage: cropRef)
return cropImage
}else {
print("error!")
return nil
}
}
//向きがおかしくなる時用
func resizeMaintainDirection(size:CGSize) -> UIImage?{
//縦横がおかしくなる時は一度書き直すと良いらしい
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
self.draw(in:CGRect(x:0,y:0,width:self.size.width,height:self.size.height))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
// リサイズ処理
let origWidth = image.size.width
let origHeight = image.size.height
var resizeWidth:CGFloat = 0
var resizeHeight:CGFloat = 0
if (origWidth < origHeight) {
resizeWidth = size.width
resizeHeight = origHeight * resizeWidth / origWidth
} else {
resizeHeight = size.height
resizeWidth = origWidth * resizeHeight / origHeight
}
let resizeSize = CGSize(width:resizeWidth, height:resizeHeight)
UIGraphicsBeginImageContext(resizeSize)
image.draw(in: CGRect(x:0,y: 0,width: resizeWidth, height: resizeHeight))
let resizeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// 切り抜き処理
let cropRect = CGRect(x:( resizeWidth - size.width ) / 2,
y:( resizeHeight - size.height) / 2,
width:size.width,
height:size.height)
if let cropRef = resizeImage?.cgImage {
cropRef.cropping(to: cropRect)
let cropImage = UIImage(cgImage: cropRef)
return cropImage
}else {
print("error!")
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment