2017-11-25 113 views
1

我在迅速和我想要生成一個函數,它在一個UIImage和的UIColor,並返回一個UIImage重新着色如何改變一個UIImage的顏色斯威夫特

我不工作一個UIImageView,這些只是我打算用作圖標的UIImage。有沒有什麼好的方法來實現這個?

回答

1

您可以使用UIGraphicsBeginImageContextWithOptions開始的圖像內容,設置所需的顏色和用圖像的方法func draw(in rect: CGRect)提醒你圖標圖像使用它的渲染模式.alwaysTemplate

extension UIImage { 
    func tinted(with color: UIColor) -> UIImage? { 
     UIGraphicsBeginImageContextWithOptions(size, false, scale) 
     defer { UIGraphicsEndImageContext() } 
     color.set() 
     withRenderingMode(.alwaysTemplate) 
      .draw(in: CGRect(origin: .zero, size: size)) 
     return UIGraphicsGetImageFromCurrentImageContext() 
    } 
} 

遊樂場測試

與PDF
let camera = UIImage(data: try! Data(contentsOf: URL(string: "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-camera-128.png")!))! 
let redCmera = camera.tinted(with: .red) 

enter image description here

+1

優秀!謝謝 – TJBlack31

1

如果使用PNG圖像(我想是因爲圖標) - 只需使用:

let originalImage = UIImage(named: "iconName") 
let tintedImage = originalImage?.withRenderingMode(.alwaysTemplate) 
yourButton.setImage(tintedImage, forState: .normal) 
yourButton.tintColor = UIColor.blue //change color of icon 
+1

模板圖像也可以。導入資源時,應該更改資產Catlog中的呈現模式。 –

+0

@derdida謝謝你的回答。這實際上是一個Google地圖標記。我可以使用類似的功能嗎? – TJBlack31

+0

正如我檢查文件,它應該與:GMSMarker.markerImage(與:UIColor.blue)來更改任何顏色的標記圖像 – derdida