簡體   English   中英

如何在 Swift 中更改 UIImage 的顏色

[英]How to change the color of a UIImage in Swift

我很快,我正在嘗試生成一個函數,該函數接受一個 UIImage 和一個 UIColor 並返回一個重新着色的 UIImage

我沒有使用 UIImageView,這些只是我打算用作圖標的 UIImages。 有什么好的方法可以實現嗎?

編輯/更新:

對於 iOS10+,我們可以使用 UIGraphicsImageRenderer:

Xcode 11 • Swift 5.1

extension UIImage {
    func tinted(with color: UIColor, isOpaque: Bool = false) -> UIImage? {
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: size, format: format).image { _ in
            color.set()
            withRenderingMode(.alwaysTemplate).draw(at: .zero) 
        }
    }
}

游樂場測試

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

原答案

您可以使用 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()
    }
}

在此處輸入圖片說明

如果您使用 PNG 圖像(因為我認為是因為圖標) - 只需使用:

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

iOS 13 及更高版本(Swift 5.1):

聲明( 見文檔

func withTintColor(_ color: UIColor) -> UIImage

用法:

yourUIImage.withTintColor(color: UIColor)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM