使用UIColor填充UIImage

使用UIColor填充UIImage

本文介绍了使用UIColor填充UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIImage 我要填写 UIColor

我试过这段代码,但应用程序在第10行崩溃。

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

这是代码:

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!
    }
}

问题可能在 context?.clip(to:rect,mask:context as!CGImage)(我想我不应该发送 context 作为掩码,但是我应该发送什么? CGImage() CGImage.self 都不起作用。

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.

推荐答案

完成绘图后需要结束图像上下文:

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

UIGraphicsEndImageContext();

或者你可以为UIImage添加一个类别方法:

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;
}

使用as:

image = [image imageByTintColor:color];

这篇关于使用UIColor填充UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:55