36 lines
1.1 KiB
Swift
36 lines
1.1 KiB
Swift
|
//
|
||
|
// UIImage.swift
|
||
|
// Mastodon
|
||
|
//
|
||
|
// Created by sxiaojian on 2021/3/8.
|
||
|
//
|
||
|
|
||
|
import UIKit
|
||
|
|
||
|
extension UIImage {
|
||
|
class func imageWithColor(color: UIColor, size: CGSize=CGSize(width: 1, height: 1)) -> UIImage? {
|
||
|
UIGraphicsBeginImageContextWithOptions(size, false, 0)
|
||
|
color.setFill()
|
||
|
UIRectFill(CGRect(origin: CGPoint.zero, size: size))
|
||
|
let image = UIGraphicsGetImageFromCurrentImageContext()
|
||
|
UIGraphicsEndImageContext()
|
||
|
return image
|
||
|
}
|
||
|
public func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
|
||
|
let maxRadius = min(size.width, size.height) / 2
|
||
|
let cornerRadius: CGFloat
|
||
|
if let radius = radius, radius > 0 && radius <= maxRadius {
|
||
|
cornerRadius = radius
|
||
|
} else {
|
||
|
cornerRadius = maxRadius
|
||
|
}
|
||
|
UIGraphicsBeginImageContextWithOptions(size, false, scale)
|
||
|
let rect = CGRect(origin: .zero, size: size)
|
||
|
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
|
||
|
draw(in: rect)
|
||
|
let image = UIGraphicsGetImageFromCurrentImageContext()
|
||
|
UIGraphicsEndImageContext()
|
||
|
return image
|
||
|
}
|
||
|
}
|