如何更改UIImage的颜色

时间:2012-05-25 13:49:10

标签: ios uiimage uicolor

我不想改变UIImage的backgroundColor,
而是改变整个图像的颜色。

因为我有标准表格,我可以从popover移动到视图 在我的应用程序中,可以将图像修改为一个大图像,即一张桌子 此外,我想将颜色改为白褐色或其他什么。

但问题是:我只能改变backgroundColor
有没有办法改变UIImage的颜色?

提前谢谢

8 个答案:

答案 0 :(得分:117)

接受的答案是正确的,但UIImageView还有更多简单方法

<强>的OBJ-C:

UIImage *image = [UIImage imageNamed:@"foo.png"];
theImageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theImageView setTintColor:[UIColor redColor]];

Swift 2:

let theImageView = UIImageView(image: UIImage(named:"foo")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))
theImageView.tintColor = UIColor.redColor()

斯威夫特3:

let theImageView = UIImageView(image: UIImage(named:"foo")!.withRenderingMode(.alwaysTemplate))
theImageView.tintColor = UIColor.red

答案 1 :(得分:58)

UIImage *image = [UIImage imageNamed:@"triangle.png"];

CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, image.CGImage);
CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage 
                                            scale:1.0 orientation: UIImageOrientationDownMirrored];

yourUIImageView.image = flippedImage;

答案 2 :(得分:5)

对于swift 3.2和4

extension UIImageView{
    func changePngColorTo(color: UIColor){
        guard let image =  self.image else {return}
        self.image = image.withRenderingMode(.alwaysTemplate)
        self.tintColor = color
    }
}

使用:

self.yourImageView.changePngColorTo(color: .red)

答案 3 :(得分:4)

您也可以使用以下代码在swift中执行此操作:

// language: Swift
let tintedImage = UIImageView(image: UIImage(named:"whatever")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate))

tintedImage.tintColor = UIColor.redColor()

答案 4 :(得分:4)

详细

  • Xcode 10.2.1(10E1001),Swift 5

方式1.扩展UIImage

来源:https://stackoverflow.com/a/40177870/4488252

extension UIImage {

    convenience init?(imageName: String) {
        self.init(named: imageName)
        accessibilityIdentifier = imageName
    }

    // https://stackoverflow.com/a/40177870/4488252
    func imageWithColor (newColor: UIColor?) -> UIImage? {

        if let newColor = newColor {
            UIGraphicsBeginImageContextWithOptions(size, false, scale)

            let context = UIGraphicsGetCurrentContext()!
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            context.setBlendMode(.normal)

            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            context.clip(to: rect, mask: cgImage!)

            newColor.setFill()
            context.fill(rect)

            let newImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            newImage.accessibilityIdentifier = accessibilityIdentifier
            return newImage
        }

        if let accessibilityIdentifier = accessibilityIdentifier {
            return UIImage(imageName: accessibilityIdentifier)
        }

        return self
    }
}

<强>用法

let imageView = UIImageView(frame: CGRect(x: 40, y: 250, width: 40, height: 40))
view.addSubview(imageView)
// Set color
imageView.image = UIImage(imageName: "Apple")?.imageWithColor(newColor: UIColor.blue)
// Reset color
//imageView.image = imageView.image?.imageWithColor(newColor: nil)

方式2.扩展UIImageView

extension UIImageView {

    var imageColor: UIColor? {
        set (newValue) {
            guard let image = image else { return }
            if newValue != nil {
                self.image = image.withRenderingMode(.alwaysTemplate)
                tintColor = newValue
            } else {
                self.image = image.withRenderingMode(.alwaysOriginal)
                tintColor = UIColor.clear
            }
        }
        get { return tintColor }
    }
}

<强>用法

let imageView = UIImageView(frame: CGRect(x: 40, y: 250, width: 40, height: 40))
view.addSubview(imageView)
imageView.image = UIImage(imageName: "Apple")
// Set color
imageView.imageColor = UIColor.green
// Reset color
//imageView.imageColor = nil

完整样本

  

不要忘记在此处粘贴上面的所有代码

import UIKit

class ImageView: UIImageView {
    enum ImageColorTransformType {
        case none, imageExtension, imageViewExtension
    }
    var imageColorTransformType = ImageColorTransformType.none
}

class ViewController: UIViewController {

    weak var colorSwitchButton: UIBarButtonItem?

    private var imageViews = [ImageView]()
    private var appleImage: UIImage { return UIImage(imageName: "apple")! }
    private var redAppleImage: UIImage { return UIImage(imageName: "red_apple")! }

    override func viewDidLoad() {
        super.viewDidLoad()
        createNewImageView(x: 40, y:100, image:appleImage, imageColorTransformType: .none)
        createNewImageView(x: 100, y:100, image:appleImage, imageColorTransformType: .imageExtension)
        createNewImageView(x: 160, y:100, image:appleImage, imageColorTransformType: .imageViewExtension)

        createNewImageView(x: 40, y:160, image:redAppleImage, imageColorTransformType: .none)
        createNewImageView(x: 100, y:160, image:redAppleImage, imageColorTransformType: .imageExtension)
        createNewImageView(x: 160, y:160, image:redAppleImage, imageColorTransformType: .imageViewExtension)

        let buttonItem = UIBarButtonItem(title: "switch", style: .plain, target: self,
                                         action: #selector(colorSwitchButtonTouchedUpInside(_:)))
        navigationItem.rightBarButtonItem = buttonItem
        colorSwitchButton = buttonItem
        useOriginalColors = false
    }

    private func createNewImageView(x:CGFloat, y: CGFloat, image: UIImage, imageColorTransformType: ImageView.ImageColorTransformType) {
        let imageView = ImageView(frame: CGRect(x: x, y: y, width: 40, height: 40))
        imageView.image = image
        imageView.imageColorTransformType = imageColorTransformType
        imageViews.append(imageView)
        view.addSubview(imageView)
    }

    private var _useOriginalColors = false
    private var useOriginalColors: Bool {
        set(value) {
            _useOriginalColors = value
            if (value) {
                navigationItem.title = "Original colors"
                for imageView in imageViews {
                    switch imageView.imageColorTransformType {
                    case .imageExtension: imageView.image = imageView.image?.imageWithColor(newColor: nil)
                    case .imageViewExtension: imageView.imageColor = nil
                    case .none: break
                    }
                }
            } else {
                navigationItem.title = "Template colors"
                for imageView in imageViews {
                    switch imageView.imageColorTransformType {
                    case .imageExtension: imageView.image = imageView.image?.imageWithColor(newColor: UIColor.blue)
                    case .imageViewExtension: imageView.imageColor = UIColor.green
                    case .none: break
                    }
                }
            }
        }
        get { return _useOriginalColors }
    }

    @objc func colorSwitchButtonTouchedUpInside(_ sender: Any) { useOriginalColors = !useOriginalColors }
}

故事板

enter image description here

结果

enter image description here enter image description here

答案 5 :(得分:0)

Swift 3 +界面构建器(故事板)

如果在界面构建器中添加了UIImageView:

myIcon.image = myIcon.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
myIcon.tintColor = UIColor.red // your color

其中myIcon是故事板的出口,例如:@IBOutlet weak var myIcon: UIImageView!

答案 6 :(得分:0)

更改UIImageView中图像的颜色:

public extension UIImageView {
    func tintImage(color: UIColor) {
        image = image?.tint(color: color)
    }
}

只需调用方法:

imageView.tintImage(color: .red)

答案 7 :(得分:0)

添加到skywinder's answer

您也可以在按钮上执行此操作:

UIImage *image = [UIImage imageNamed:@"foo.png"];
[myButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
[myButton setTintColor:[UIColor redColor]];