[Swift] 如何將顏色轉為圖檔?

在 iOS 的開發上,有時後將顏色轉為圖檔 (UIColor to UIImage) 是一個常見的案例,而 Swift 將顏色轉為圖檔的方式也相當簡單,只要短短幾行,就可以輕鬆辦到了。趕快來看這神奇的程式吧!

swift
extension UIColor {
 
    func toUIImage() -> UIImage?{
        let width = UIScreen.main.bounds.size.width
        let height = UIScreen.main.bounds.size.height
        let rect = CGRect(origin: .zero, size: CGSize(width: width, height: height))
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
        setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
 
        guard let cgImage = image?.cgImage else { return nil }
        return UIImage(cgImage: cgImage)
    }
}

那麼,接下來你會怎麼用呢?就依底下的用法用就好了。

let color: UIColor = .white
let image = color.toUIImage() 

這樣的寫法是我覺得最單純而且最容易的寫法了,大家可以參考看看唷!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments