iphone - drawRect 中的多个 CGContextRef

标签 iphone objective-c ios ipad cocoa-touch

在重写 UIView drawRect 时,我使用 CGContextDrawImage 绘制主图像。在它上面我需要绘制另一个图像(使用多重混合模式),所以我实际上需要在它上面绘制。

第二个图像需要准备,因为它是动态生成的(它必须被屏蔽,可能大小不同等等),所以最后我需要生成它。如何获得第二个上下文,在将第二个图像应用到主图像上之前,我可以在其中绘制并 mask 第二个图像?如果我在当前上下文上进行绘制,那么在我可以屏蔽它之前,它会直接绘制到主上下文中。

- (void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextDrawImage(ctx, CGRectMake(0, 0, rect.size.width, rect.size.height), [UIImage imageNamed:@"actionBg.png"].CGImage);

    // prevent the drawings to be flipped
    CGContextTranslateCTM(ctx, 0, rect.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    // generate the overlay
    if ([self isActive] == NO && self.fullDelay != 0) { // TODO: remove fullDelay check!
        int segmentSize = (ACTION_SIZE / [self fullDelay]);

        for (int i=0; i<[self fullDelay]; i++) {
            float alpha = 0.9 - (([self fullDelay] * 0.1) - (i * 0.1));
            [[UIColor colorWithRed:120.0/255.0 green:14.0/255.0 blue:14.0/255.0 alpha:alpha] setFill];

            if (currentDelay > i) {
                CGRect r = CGRectMake(0, i * segmentSize, ACTION_SIZE, segmentSize);
                CGContextFillRect(ctx, r);
            }
            [[UIColor colorWithRed:1 green:1 blue:1 alpha:0.3] setFill];
            CGRect line = CGRectMake(0, (i * segmentSize) + segmentSize - 1 , ACTION_SIZE, 1);
            CGContextFillRect(ctx, line);
        }

        UIImage *overlay = UIGraphicsGetImageFromCurrentImageContext();
        UIImage *overlayMasked = [TDUtilities maskImage:overlay withMask:[UIImage imageNamed:@"actionMask.png"]];
    }
}

这里的overlayMasked现在包含正确的图像,但由于我已经使用主上下文准备了它,所以它并不完全困惑。谢谢

谢谢

最佳答案

您可以使用 UIGraphicsBeginImageContextWithOptions 创建位图上下文或CGBitmapContextCreate 。在位图上下文中完成绘制后,您可以使用 UIGraphicsGetImageFromCurrentImageContextCGBitmapContextCreateImage (根据需要)获取图像,然后使用 UIGraphicsEndImageContext 释放上下文CGContextRelease

关于iphone - drawRect 中的多个 CGContextRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13579149/

相关文章:

iPhone iOS 如何将文本从 UITextView 导出到文本文件以进行跨平台编辑? (Mac、PC、iPhone 等)

objective-c - NSOperation子类发布使Instruments崩溃

objective-c - 关于 "Semantic Issue"的编译器警告——如何解决?

ios - For循环不改变变量

ios - 在 Swift 中使用 Alamofire 处理 XML 数据

iphone - 从异步更新文本字段返回 - iPhone

iphone - 如何创建在选项卡之间切换时保留在屏幕上的 View ?

iphone - 无法在 iPhone 上测试应用程序

iphone - iOS 应用程序提交期间要求的 Bundle ID 域扩展

objective-c - 为什么在尝试将 UIWebView 添加到此 ViewController 头文件时会出现这些错误?