iOS/코드조각

[iOS, Swift] UIImage 그라데이션 그리기 (Gradient Image)

검은참깨두유vm 2022. 8. 21. 11:07
반응형

iOS 15.5, Xcode 13.31, Swift 5, UIKit 환경에서 진행했습니다.

 

extension UIImage {
    static func gradientImageWithBounds(bounds: CGRect, colors: [CGColor]) -> UIImage {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = colors
        
        UIGraphicsBeginImageContext(gradientLayer.bounds.size)
        gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
}

 

let image = UIImage.gradientImageWithBounds(bounds: CGRect(x: 0, y: 0, width: 200, height: 200), colors: [UIColor.yellow.cgColor, UIColor.blue.cgColor])
        
let imageView = UIImageView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
imageView.image = image

 

반응형