2

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

编辑:示例代码(宽度和高度是预定义的浮点数,点是一个 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

4

1 回答 1

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

要解决这个问题。

于 2011-11-11T10:28:03.853 回答