美文网首页iOS开发知识小集
【第10期】iOS修改图片的颜色

【第10期】iOS修改图片的颜色

作者: 天天乐视 | 来源:发表于2020-01-07 10:33 被阅读0次

    关注微信公众号【科技小弟】,了解第一手iOS小知识。

    今天介绍一下怎么修改图片的颜色。

    .h文件代码:
    科技小弟(https://www.jianshu.com/u/23c527245f22)

    #import <UIKit/UIKit.h>
    
    @interface UIImage (YYChangePictureColor)
    
    /**
     *  修改图片颜色(如何使用:[[UIImage imageNamed:@"image"] imageWithTintColor:[UIColor orangeColor]]; )
     *
     *  @param tintColor 指定颜色
     *
     *  @return 图片
     */
    - (UIImage *)imageWithTintColor:(UIColor *)tintColor;
    - (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor;​
    
    @end
    

    .m文件代码:

    #import "UIImage+YYChangePictureColor.h"​
    
    @implementation UIImage (YYChangePictureColor)
    
    - (UIImage *)imageWithTintColor:(UIColor *)tintColor {
    
        return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
    }
    
    - (UIImage *)imageWithGradientTintColor:(UIColor *)tintColor {
    
        return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
    }
    
    - (UIImage *)imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode {
    
        //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
        UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
        [tintColor setFill];
        CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
        UIRectFill(bounds);
    
    //Draw the tinted image in context
        [self drawInRect:bounds blendMode:blendMode alpha:1.0f];
    
        if (blendMode != kCGBlendModeDestinationIn) {
        
            [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
        }
        
        UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return tintedImage;
    }
    
    @end
    

    怎么使用?我们先找一张图片:

    1

    这是一个白色图标,用于后退按钮,如果我们想把它改成其他颜色呢?

    比如我们想把它改成蓝色,调用:

    [_backButton setImage:[[UIImage imageNamed:@"common_back"] imageWithTintColor:[UIColor blueColor]] forState:UIControlStateNormal];
    

    结果展示:

    2

    看,它已经变成蓝色了,完美!

    相关文章

      网友评论

        本文标题:【第10期】iOS修改图片的颜色

        本文链接:https://www.haomeiwen.com/subject/sqkractx.html