【问题标题】:Color overlay on specific area of UIImageUIImage特定区域的颜色叠加
【发布时间】:2013-04-21 20:44:01
【问题描述】:

我正在尝试在 UIImage 上叠加颜色,但仅在图像的左半部分(我使用来自 http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage 的代码来叠加颜色)。我现在的代码是:

- (UIImage *)imageWithColor:(UIColor *)color{

// begin a new image context, to draw our colored image onto
CGSize size = CGSizeMake(self.line.image.size.width/2, self.line.image.size.height);
UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);

// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();

// set the fill color
[color setFill];

// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);

// set the blend mode to overlay, and the original image
CGContextSetBlendMode(context, kCGBlendModeOverlay);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
CGContextDrawImage(context, rect, self.line.image.CGImage);

// set a mask that matches the shape of the image, then draw (overlay) a colored rectangle
CGContextClipToMask(context, rect, self.line.image.CGImage);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);

// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//return the color-burned image
return coloredImg;
}

我认为将大小设置为宽度的一半会起作用,但一切仍然会着色。我想我错过了一些非常基本的东西。有什么想法吗?

【问题讨论】:

    标签: ios uiimage


    【解决方案1】:

    CGContextAddRect(context, rect);
    

    您正在添加一个全尺寸的矩形。

    【讨论】:

    • 矩形应该使用我上面定义的 size.width 吧?
    • 我想是的——这就是你想要的吗?
    • 是的,尺寸是用(图像尺寸)/2 的宽度制成的。矩形是用那个 size.width 制作的。但是整个图像仍然被颜色覆盖。
    • 没错。您使用的是 rect 而不是 size。
    • 我将矩形定义为宽度为(图像大小)/2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多