【问题标题】:Colourise CGContextRef But Preserve Alpha着色 CGContextRef 但保留 Alpha
【发布时间】:2011-11-03 20:50:37
【问题描述】:

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

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

【问题讨论】:

  • 您能给我们一些示例代码,以便我们更好地了解您的问题吗?
  • 好吧,这有帮助。我试图掌握你的想法,所以请告诉我我是否正确。从我在这里看到的是,您正在尝试绘制带有黑色边框的白色矩形而没有透明度。然后你做一个未知的功能 [color setFill];我不知道它的作用(即使名称不言自明,您也可能想给我们提供那条信息)。然后,您将在先前矩形的顶部绘制另一条具有相同尺寸的路径。然后,您想获取绘图并将其存储在该图像变量中。
  • 现在澄清一下:kCGBlendModeMultiply 将源图像样本与背景图像样本相乘。这导致颜色至少与两种贡献样本颜色中的任何一种颜色一样深。所以你可能还是想使用另一个。尝试将其设置为正常并发布结果。另外:如果您对 alpha 有疑问,请尝试使用以下函数手动将其设置为上下文:CGContextSetAlpha (CGContextRef c, CGFloat alpha);试一试并在此处发布结果。
  • 我希望白色四边形的黑色边框具有 alpha 1 和背景具有 alpha 0 - 我实现了这一点。但是,我正在尝试拍摄此图像并应用颜色,同时不更改上下文的 alpha。我还应该试试你的建议吗? BTW [color setFill] 使 UIColor 成为当前上下文的填充颜色。
  • 我不是很了解你,但也许它有帮助 CGContextStrokePath(context); CGContextFillPath(上下文);还有一个developers-life.com/color-picker-for-ios.html - 例如,从图像中获取颜色

标签: iphone objective-c alpha cgcontext colorize


【解决方案1】:

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

修复它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 2010-10-26
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多