// // UIImageExtensions.swift // CapFinder // // Created by User on 13.02.18. // Copyright © 2018 User. All rights reserved. // import Foundation import UIKit extension UIImage { static func templateImage(named: String) -> UIImage { return UIImage(named: named)!.withRenderingMode(.alwaysTemplate) } /** Resize an image to the target size */ func resize(to targetSize: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height) UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0) self.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } /** Crop an image to a square, centered around the middle of the frame - parameter factor: The crop factor of the resulting image - returns: The cropped image */ func crop(factor: CGFloat) -> UIImage { let width = self.size.width * factor return crop(to: width) } /** Crop an image to a square, centered around the middle of the frame - parameter size: The height and width of the resulting image - returns: The cropped image */ func crop(to size: CGFloat) -> UIImage { var rect = CGRect( x: (self.size.height - size) / 2, y: (self.size.width - size) / 2, width: size, height: size) rect.origin.x *= scale rect.origin.y *= scale rect.size.width *= scale rect.size.height *= scale let imageRef = cgImage!.cropping(to: rect) return UIImage(cgImage: imageRef!, scale: scale, orientation: imageOrientation) } /// The (circular) image masked by a circle var circleMasked: UIImage? { let width = size.width let height = size.height let isPortrait = height > width let breadth = min(width, height) let breadthSize = CGSize(width: breadth, height: breadth) let breadthRect = CGRect(origin: .zero, size: breadthSize) UIGraphicsBeginImageContextWithOptions(breadthSize, false, scale) defer { UIGraphicsEndImageContext() } let x = isPortrait ? 0 : floor((width - height) / 2) let y = isPortrait ? floor((height - width) / 2) : 0 let rect = CGRect(origin: CGPoint( x: x, y: y), size: breadthSize) guard let cgImage = cgImage?.cropping(to: rect) else { return nil } UIBezierPath(ovalIn: breadthRect).addClip() UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation).draw(in: breadthRect) return UIGraphicsGetImageFromCurrentImageContext() } }