##実装コード
UIImage+flip.swift
import UIKit
extension UIImage {
let scale = 1.0
//上下反転
func flipVertical() -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let imageRef = self.cgImage
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: 0)
context?.scaleBy(x: 1.0, y: 1.0)
context?.draw(imageRef!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let flipHorizontalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return flipHorizontalImage!
}
//左右反転
func flipHorizontal() -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let imageRef = self.cgImage
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: size.width, y: size.height)
context?.scaleBy(x: -1.0, y: -1.0)
context?.draw(imageRef!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let flipHorizontalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return flipHorizontalImage!
}
}
##使用方法
extensionで実装していますので以下のように呼び出せます。
let flipImage = image.flipVertical()
let flipImage = image.flipHorizontal()