UIImage+CoreGraphics.swift
import UIKit
extension UIImage {
//Preparation
private func preprare(size: CGSize, _ draw: (() -> Void)? = nil) -> UIImage! {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
draw?()
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
func resize(ratio: CGFloat) -> UIImage! {
let size = CGSize(width: self.size.width * ratio, height: self.size.height * ratio)
return self.resize(size: size)
}
func resize(height: CGFloat) -> UIImage! {
let width = self.size.width * height / self.size.height
let size = CGSize(width: width, height: height)
return self.resize(size: size)
}
func resize(width: CGFloat) -> UIImage! {
let height = self.size.height * width / self.size.width
let size = CGSize(width: width, height: height)
return self.resize(size: size)
}
func resize(size: CGSize) -> UIImage! {
preprare(size: size) {
self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
}
}
func compose(image: UIImage, frame: CGRect) -> UIImage! {
preprare(size: self.size) {
self.draw(at: .zero)
image.draw(in: frame)
}
}
func compose(image: UIImage, atCenter: CGPoint, blendMode: CGBlendMode = .copy, alpha: CGFloat = 1.0) -> UIImage! {
preprare(size: self.size) {
self.draw(at: .zero)
let at = CGPoint(x: atCenter.x - image.size.width/2, y: atCenter.y - image.size.height/2)
image.draw(at: at, blendMode: blendMode, alpha: alpha)
}
}
func compose(image: UIImage, at: CGPoint, blendMode: CGBlendMode = .copy, alpha: CGFloat = 1.0) -> UIImage! {
preprare(size: self.size) {
self.draw(at: .zero)
image.draw(at: at, blendMode: blendMode, alpha: alpha)
}
}
}
Recommended Posts