search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Swift] 如何將顏色轉為圖檔? - 海芋小站

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

 

swift

 

為了方便使用,我們先來寫一個 UIColor 的擴充,其中 width 和 height 請置換成您想要要寬度或高度。

  • extension UIColor {
  •  
  •     func toUIImage() -> UIImage?{
  •         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()

 

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



熱門推薦

本文由 inote 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦