如何在iOS和WatchKit中更改图像tintColor

我有一个名为“theImageView”的UIImageView,UIImage为单色(透明背景),就像下面的左黑心一样。如何根据iOS 7+导航栏图标中使用的色调方法在iOS 7或更高版本中以编程方式更改此图像的色调?


这种方法也适用于Apple Watch应用程序的WatchKit吗?


收到一只叮咚
浏览 614回答 3
3回答

动漫人物

这是一个应该做的技巧@interface UIImage(Overlay)@end@implementation UIImage(Overlay)- (UIImage *)imageWithColor:(UIColor *)color1{        UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);        CGContextRef context = UIGraphicsGetCurrentContext();        CGContextTranslateCTM(context, 0, self.size.height);        CGContextScaleCTM(context, 1.0, -1.0);        CGContextSetBlendMode(context, kCGBlendModeNormal);        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);        CGContextClipToMask(context, rect, self.CGImage);        [color1 setFill];        CGContextFillRect(context, rect);        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();        UIGraphicsEndImageContext();        return newImage;}@end所以你会这样做:theImageView.image = [theImageView.image imageWithColor:[UIColor redColor]];

蛊毒传说

我必须在Swift中使用extension。我以为我会分享我是如何做到的:extension UIImage {    func imageWithColor(color1: UIColor) -> UIImage {        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)        color1.setFill()        let context = UIGraphicsGetCurrentContext() as CGContextRef        CGContextTranslateCTM(context, 0, self.size.height)        CGContextScaleCTM(context, 1.0, -1.0);        CGContextSetBlendMode(context, CGBlendMode.Normal)        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect        CGContextClipToMask(context, rect, self.CGImage)        CGContextFillRect(context, rect)        let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage        UIGraphicsEndImageContext()        return newImage    }}用法:theImageView.image = theImageView.image.imageWithColor(UIColor.redColor())斯威夫特4extension UIImage {    func imageWithColor(color1: UIColor) -> UIImage {        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)        color1.setFill()        let context = UIGraphicsGetCurrentContext()        context?.translateBy(x: 0, y: self.size.height)        context?.scaleBy(x: 1.0, y: -1.0)        context?.setBlendMode(CGBlendMode.normal)        let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))        context?.clip(to: rect, mask: self.cgImage!)        context?.fill(rect)        let newImage = UIGraphicsGetImageFromCurrentImageContext()        UIGraphicsEndImageContext()        return newImage!    }}用法:theImageView.image = theImageView.image?.imageWithColor(color1: UIColor.red)
打开App,查看更多内容
随时随地看视频慕课网APP