【问题标题】:UIImage overlay with color: bad result带有颜色的 UIImage 叠加层:结果不好
【发布时间】:2014-02-12 09:20:05
【问题描述】:

我需要用纯色覆盖一个小 png。 我使用的代码是:

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

}

但结果不是很流畅...这里是原始图像(黑色)和带有叠加层的图像(白色)

【问题讨论】:

    标签: ios uiimage core-graphics


    【解决方案1】:

    我会这样做的方式如下(假设你是 iOS7-only): 反转原始图像:在 Photoshop 或类似的工具中编辑它,使黑线是透明的(alpha),而空白不是(不管它是什么颜色,只要它不透明)。 然后在代码中:

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

    其中 imageView 是包含您的图像的视图。

    【讨论】:

      【解决方案2】:

      问题是您正在使用这行代码创建一个非视网膜(比例因子为 1.0)的图形上下文

      UIGraphicsBeginImageContext(self.size);
      

      你可以在文档中看到这个

      这个函数相当于调用UIGraphicsBeginImageContextWithOptions函数,opaque参数设置为NO,比例因子为1.0。

      相反,您应该直接使用UIGraphicsBeginImageContextWithOptions 并为比例因子传递 0.0(据记录与主屏幕的比例因子相同):

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

      即你应该使用:

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

      【讨论】:

        猜你喜欢
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 1970-01-01
        相关资源
        最近更新 更多