[SWIFT] This and that of Core Graphics

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

This and that of Core Graphics
This and that of the JDK
This and that of exclusive control
This and that of Swift corner Radius
This and that of conditional branching of rails development
Docker settings and this and that
[Rails] strftime this and that
Digital certificate this and that
Base64 encoder this and that
I tried to verify this and that of Spring @ Transactional
This and that about Base64 (Java)
This and that of the implementation of date judgment within the period in Java
This and that for editing ini in Java. : inieditor-java
behavior of didSet and willSet
Overview of Docker and containers
Background and mechanism of Fabric-loader
Summary of FileInputStream and BufferedInputStream
Combination of search and each_with_index
Judgment of JSONArray and JSONObject
Operator of remainder and exponentiation (exponentiation)
Advantages and disadvantages of Java