Colourise CGContextRef但保留Alpha

时间:2011-11-03 20:50:38

标签: iphone objective-c alpha cgcontext colorize

我有一个CGContextRef,可以在上面绘制并指定alpha,如果我尝试使用它,它就能完美运行。但是,我正在尝试着色它(目前是红色或绿色),但无论我选择何种混合模式,alpha都设置为1(因为我使用alpha绘制1)。绘制正确的颜色并不是一个可行的选择,因为我希望能够从文件系统中加载UIImage颜色,所以我该如何实现呢?

编辑:示例代码(宽度和高度是预定义的浮点数,点是CGPoints的数组,所有这些都位于上下文中,颜色是不透明度为100%的UIColor) -

UIGraphicsBeginImageContext(CGSizeMake(width,height));

CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGContextClearRect(contextRef, CGRectMake(0.0f, 0.0f, width, height));
CGContextSetRGBStrokeColor(contextRef, 0.0f, 0.0f, 0.0f, 1.0f);
CGContextSetRGBFillColor(contextRef, 1.0f, 1.0f, 1.0f, 1.0f);
CGContextSetLineWidth(contextRef, lineWidth);

CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, points[0].x, points[0].y);
for (int i = 1; i < 4; i++) {
    CGContextAddLineToPoint(contextRef, points[i].x, points[i].y);
}
CGContextAddLineToPoint(contextRef, points[0].x, points[0].y); // Encloses shape

CGContextDrawPath(contextRef, kCGPathFillStroke);

[color setFill];

CGContextBeginPath(contextRef);
CGContextSetBlendMode(contextRef, kCGBlendModeMultiply);
CGContextAddRect(contextRef, CGRectMake(0.0f, 0.0f, width, height));
CGContextDrawPath(contextRef, kCGPathFill);

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

提前感谢您的帮助,
jrtc27

1 个答案:

答案 0 :(得分:2)

问题是我需要CGContextClipToMask。这意味着我的代码需要以下内容:

CGContextTranslateCTM(contextRef, 0, height);
CGContextScaleCTM(contextRef, 1.0, -1.0);

转换坐标然后

CGRect rect = CGRectMake(0.0f, 0.0f, width, height);
CGContextClipToMask(contextRef, rect, UIGraphicsGetImageFromCurrentImageContext().CGImage);

修复它。

相关问题