iOS:使用CoreGraphics进行2步图像处理

Cha*_*bot 8 iphone core-graphics objective-c cgcontext ios

使用CoreGraphics(在我的drawRect方法中),我正在尝试将混合模式应用于图像(透明png),然后调整结果的alpha.我假设这需要分两步完成,但我可能错了.这是我到目前为止(工作正常):

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);

//SET COLOR - EDIT... added a more practical color example
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1);

//flips drawing context (apparently this is necessary)
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);//flip context

//DRAW PIN IMAGE
UIImage *pin = [UIImage imageNamed:@"pin"];
CGRect pinrect = CGRectMake(12, 17, 25, 25);    
CGContextDrawImage(context, pinrect, pin.CGImage);//draws image in context

//Apply blend mode
CGContextSetBlendMode(context, kCGBlendModeColor); 
CGContextClipToMask(context, pinrect, pin.CGImage); // restricts drawing to within alpha channel

//fills context with mask, applying blend mode
CGContextFillRect(context, pinrect); 

CGContextRestoreGState(context);

// -- Do something here to make result 50% transparent ?? --
Run Code Online (Sandbox Code Playgroud)

我假设我需要将所有这些绘制到某个单独的上下文中,调用 CGContextSetAlpha(...),然后将其重新绘制回原始上下文,但我不确定如何.在我的最终CGContextFillRect之前设置alpha只会改变应用混合模式的数量,而不是整个图像的alpha.

编辑:截图发布

在此输入图像描述

提前致谢.

ugh*_*fhw 9

使用透明层,可以将混合应用于以100%绘制的图像,并将结果显示为50%.结果如下:
图像显示输出 我使用带纹理的背景,这样你就可以清楚地看到下面的图像对所有东西都是50%透明,而不是像我之前尝试的那样只是另一张图像.这是代码:

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);//flip context

CGRect fullImageRect = (CGRect){42,57,100,100};
CGRect transparentImageRect = (CGRect){12,17,100,100};
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1);

// Draw image at 100%
UIImage *testImage = [UIImage imageNamed:@"TestImage"];
CGContextDrawImage(context,fullImageRect,testImage.CGImage);

// Set 50% transparency and begin a transparency layer. Inside the transparency layer, the alpha is automatically reset to 1.0
CGContextSetAlpha(context,0.5);
CGContextBeginTransparencyLayer(context, NULL);
// Draw the image. It is viewed at 100% within the transparency layer and 50% outside the transparency layer.
CGContextDrawImage(context, transparentImageRect, testImage.CGImage);
// Draw blend on top of image
CGContextClipToMask(context, transparentImageRect, testImage.CGImage);
CGContextSetBlendMode(context, kCGBlendModeColor);
CGContextFillRect(context, transparentImageRect);
// Exit transparency layer, causing the image and blend to be composited at 50%.
CGContextEndTransparencyLayer(context);
Run Code Online (Sandbox Code Playgroud)

编辑:删除旧内容,因为它占用了大量空间并且没有帮助.如果要查看,请查看修订历史记录.