给CGContextRef上色,但保留Alpha



我有一个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

问题是我需要一个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);

最新更新