由于種種原因儿奶,簡(jiǎn)書(shū)等第三方平臺(tái)博客不再保證能夠同步更新宝与,歡迎移步 GitHub:https://github.com/kingcos/Perspective/喜滨。謝謝捉捅!
UIColor <-> UIImage
- Info:
- macOS 10.12.1
- Xcode 8.1
- Swift 3.0
前言
在平時(shí)的練習(xí)中,經(jīng)常需要使用 UIImage虽风,但圖片又不好找棒口。為了解決這個(gè)問(wèn)題,我想到了使用 UIColor 生成 UIImage辜膝。該部分的具體知識(shí)涉及到 Core Graphics无牵,也是一個(gè)新的知識(shí)點(diǎn)。在網(wǎng)上尋找一番厂抖,只有 Objective-C 版本合敦,這次使用 Swift 3.0 進(jìn)行重寫(xiě)。
Code
func generateImageWith(_ color: UIColor, andFrame frame: CGRect) -> UIImage? {
// 開(kāi)始繪圖
UIGraphicsBeginImageContext(frame.size)
// 獲取繪圖上下文
let context = UIGraphicsGetCurrentContext()
// 設(shè)置填充顏色
context?.setFillColor(color.cgColor)
// 使用填充顏色填充區(qū)域
context?.fill(frame)
// 獲取繪制的圖像
let image = UIGraphicsGetImageFromCurrentImageContext()
// 結(jié)束繪圖
UIGraphicsEndImageContext()
return image
}
使用時(shí)直接調(diào)用該方法验游,并傳入相應(yīng)參數(shù)即可,那么反過(guò)來(lái)呢保檐?
let color = UIColor(patternImage: image!)
這樣就可以從圖片獲取顏色耕蝉。