有没有办法改变图像的颜色而不会丢失它上面的图案

时间:2012-01-27 10:26:34

标签: iphone objective-c ipad

有没有办法改变图像的颜色,而不会丢失它上面的图案?

1 个答案:

答案 0 :(得分:6)

试试这个(UIImage的类别):

·H

@interface UIImage (Overlay)

- (UIImage *)imageWithOverlayColor:(UIColor *)color;

@end

的.m

#import "UIImage+Overlay.h"

@implementation UIImage (Overlay)

- (UIImage *)imageWithOverlayColor:(UIColor *)color
{        
    CGRect rect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);

    if (UIGraphicsBeginImageContextWithOptions) {
        CGFloat imageScale = 1.0f;
        if ([self respondsToSelector:@selector(scale)])  // The scale property is new with iOS4.
            imageScale = self.scale;
        UIGraphicsBeginImageContextWithOptions(self.size, NO, imageScale);
    }
    else {
        UIGraphicsBeginImageContext(self.size);
    }

//    [self drawInRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeMultiply);
       CGContextDrawImage(context, rect, self.CGImage);
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextClipToMask(context, rect, self.CGImage);
    CGContextFillRect(context, rect);   

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

@end

这样称呼:

UIImage *image = [UIImage imageNamed:@"image.png"]; 
image = [image imageWithOverlayColor:[UIColor redColor]];

图像之前和之后: