2014-02-12 41 views
0

我需要覆盖一个平坦的颜色的小PNG。 我使用的代码是:UIImage覆盖颜色:效果不好

- (UIImage *)overlayWithColor:(UIColor *)overlayColor { 


    UIGraphicsBeginImageContext(self.size); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 


    [overlayColor setFill]; 

    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); 
    CGContextDrawImage(context, rect, self.CGImage); 


    CGContextClipToMask(context, rect, self.CGImage); 
    CGContextAddRect(context, rect); 
    CGContextDrawPath(context,kCGPathFill); 

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

    return coloredImg; 

} 

但结果不是很顺畅......这里的原始图像(黑的),并在重叠的图像(白色的)

enter image description here enter image description here

回答

1

我会这样做的方式如下(假设你只是iOS7): 反转原始图像:在Photoshop中编辑或类似的东西,使黑色线条是透明的(alpha),白色空间不是(它无关紧要,只要它不透明)。 然后在代码:

imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; 
[imageView.image setTintColor:[UIColor orangeColor]]; 

哪里ImageView的是查看包含你的形象。

1

的问题是,你正在创建一个非视网膜(带刻度系数1.0)的图形上下文与这行代码

UIGraphicsBeginImageContext(self.size); 

您可以将文档

此功能在看到这相当于调用UIGraphicsBeginImageContextWithOptions函数,将opaque参数设置为NO并且缩放因子为1.0。

相反,你应该直接使用UIGraphicsBeginImageContextWithOptions,并通过为比例系数为0.0(这是记录是相同主屏幕的比例因子):

如果指定的0.0值,比例因子被设置为设备主屏幕的比例因子。

I.e.您应该使用:

UIGraphicsBeginImageContextWithOptions(self.size, 
             NO, // opaque or not. NO means transparent 
             0.0); // scale factor. 0 means same as device