85 lines
3.1 KiB
Swift
85 lines
3.1 KiB
Swift
//
|
|
// UIImage.swift
|
|
// List
|
|
//
|
|
// Created by Igor Danich on 20.07.2020.
|
|
// Copyright © 2020 Igor Danich. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
|
|
// MARK: - REFACTOR
|
|
|
|
extension UIImage {
|
|
static func colored(_ color: UIColor, size: CGSize, cornerRadius: CGFloat = 0) -> UIImage {
|
|
draw(size: size) { (size, _) in
|
|
color.setFill()
|
|
UIBezierPath(roundedRect: .init(x: 0, y: 0, width: size.width,
|
|
height: size.height),
|
|
cornerRadius: cornerRadius)
|
|
.fill()
|
|
}
|
|
}
|
|
static func draw(size: CGSize, scale: CGFloat = UIScreen.main.scale, _ completion: (CGSize,CGContext) -> Void) -> UIImage {
|
|
var size = size
|
|
if size.width == 0 { size.width = 1 }
|
|
if size.height == 0 { size.height = 1 }
|
|
UIGraphicsBeginImageContextWithOptions(size, false, scale)
|
|
if let context = UIGraphicsGetCurrentContext() { completion(size, context) }
|
|
defer { UIGraphicsEndImageContext() }
|
|
return UIGraphicsGetImageFromCurrentImageContext()!
|
|
}
|
|
}
|
|
|
|
extension UIImage {
|
|
func tinted(with color: UIColor) -> UIImage? {
|
|
UIGraphicsBeginImageContextWithOptions(size, false, scale)
|
|
defer { UIGraphicsEndImageContext() }
|
|
color.set()
|
|
withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: size))
|
|
return UIGraphicsGetImageFromCurrentImageContext()
|
|
}
|
|
}
|
|
|
|
extension UIImage {
|
|
func rotate(radians: CGFloat) -> UIImage {
|
|
let rotatedSize = CGRect(origin: .zero, size: size)
|
|
.applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
|
|
.integral.size
|
|
UIGraphicsBeginImageContext(rotatedSize)
|
|
if let context = UIGraphicsGetCurrentContext() {
|
|
let origin = CGPoint(x: rotatedSize.width / 2.0,
|
|
y: rotatedSize.height / 2.0)
|
|
context.translateBy(x: origin.x, y: origin.y)
|
|
context.rotate(by: radians)
|
|
draw(in: CGRect(x: -origin.y, y: -origin.x,
|
|
width: size.width, height: size.height))
|
|
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
|
|
UIGraphicsEndImageContext()
|
|
|
|
return rotatedImage ?? self
|
|
}
|
|
|
|
return self
|
|
}
|
|
}
|
|
|
|
extension String {
|
|
func generateQRCode(tintColor: UIColor? = nil) -> UIImage? {
|
|
let stringData = data(using: .utf8)
|
|
let filter = CIFilter(name: "CIQRCodeGenerator")
|
|
filter?.setValue(stringData, forKey: "inputMessage")
|
|
filter?.setValue("H", forKey: "inputCorrectionLevel")
|
|
if let tintColor = tintColor {
|
|
if let ciImage = filter?.outputImage?.transformed(by: CGAffineTransform(scaleX: 5, y: 5)).tinted(using: tintColor) {
|
|
return UIImage(ciImage: ciImage, scale: UIScreen.main.scale, orientation: .down)
|
|
}
|
|
} else {
|
|
if let ciImage = filter?.outputImage?.transformed(by: CGAffineTransform(scaleX: 5, y: 5)) {
|
|
return UIImage(ciImage: ciImage, scale: UIScreen.main.scale, orientation: .down)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|