Swift 漸變 image

Brocadecarp發表於2018-04-23

6519E848-0C43-430A-AA96-F6A5A031D993.png

// 擴充套件 UIImage 的 init 方法,獲得漸變效果
public extension UIImage {
    convenience init?(gradientColors:[UIColor], size:CGSize = CGSizeMake(10, 10) )
    {
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        let context = UIGraphicsGetCurrentContext()
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let colors = gradientColors.map {(color: UIColor) -> AnyObject! in return color.CGColor as AnyObject! } as NSArray
        let gradient = CGGradientCreateWithColors(colorSpace, colors, nil)
        // 第二個引數是起始位置,第三個引數是終止位置
        CGContextDrawLinearGradient(context, gradient, CGPoint(x: 0, y: 0), CGPoint(x: size.width, y: 0), CGGradientDrawingOptions(rawValue: 0))
        self.init(CGImage:UIGraphicsGetImageFromCurrentImageContext().CGImage!)
        UIGraphicsEndImageContext()
    }
}
複製程式碼

相關文章