Fill UIImage with UIColor

2019-04-15 07:29发布

I have a UIImage that I want to fill with UIColor

I've tried this code but the app crashes on the 10th row.

Here's the code:

extension  UIImage {
    func imageWithColor(_ color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()
        context?.translateBy(x: 0.0, y: size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.setBlendMode(CGBlendMode.normal)
        let rect = CGRect(origin: CGPoint.zero, size: size)
        context?.clip(to: rect, mask: context as! CGImage)// crashes
        color.setFill()
        context?.fill(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        return newImage!
    }
}

The problem is probably on context?.clip(to: rect, mask: context as! CGImage) (I think I shouldn't send context as the mask, but what should I send? Both CGImage() and CGImage.self don't work.

4条回答
Rolldiameter
2楼-- · 2019-04-15 07:48
let image = UIImage(named: "whatever.png")?.imageWithRenderingMode(.alwaysTemplate)

When you set this image later to UIButton or UIImageView - just change tint color of that control, and image will be drawn using tint color you specified.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-15 07:52

You have to do as follow:

extension UIImage {
    func tinted(with color: UIColor) -> UIImage? {
        defer { UIGraphicsEndImageContext() }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        color.set()
        withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}
查看更多
走好不送
4楼-- · 2019-04-15 07:57

Simplest way to doing this

theImageView.image? = (theImageView.image?.imageWithRenderingMode(.AlwaysTemplate))! 
theImageView.tintColor = UIColor.magentaColor()
查看更多
劳资没心,怎么记你
5楼-- · 2019-04-15 07:59

You need to end the image context when you finish drawing:

UIGraphicsEndImageContext();

Or you could add a category method for UIImage:

- (UIImage *)imageByTintColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    [color set];
    UIRectFill(rect);
    [self drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeDestinationIn alpha:1];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

Using as:

image = [image imageByTintColor:color];
查看更多
登录 后发表回答