0

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

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

- (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 现在包含正确的图像,但由于我已经使用主要上下文准备了它,所以它并不是一团糟。谢谢

谢谢

4

1 回答 1

1

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

于 2012-11-27T07:27:01.693 回答