【问题标题】:Core Graphics questions regarding context. CGContextFillRects: invalid context 0xa88a500关于上下文的核心图形问题。 CGContextFillRects:无效的上下文 0xa88a500
【发布时间】:2012-11-20 08:50:29
【问题描述】:

通常当您在无效上下文中绘制时,您会看到类似于无效上下文 0x00 的内容,但情况并非如此,因为我看到了一个地址。我所有的核心图形代码都在视图的 drawRect 内。 有时,并非总是如此,我看到: “:CGContextFillRects:无效的上下文0xa88a500” 有时我的代码似乎有效,但其他代码却失败了。 我想画的是面具之类的东西。

如果您发现这里有什么问题,可以告诉我吗?:

UIGraphicsBeginImageContext(rect.size); CGContextRef 上下文 = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]); CGContextFillRect(context, rect);

switch (shape) {
    case SHAPE_ELIPSE:
        //
        CGContextAddEllipseInRect(context, maskBox);
        CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
        CGContextFillEllipseInRect(context, maskBox);
        break;
    case SHAPE_SQUARE:
        //
        CGContextAddRect(context, maskBox);
        CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
        CGContextFillRect(context, maskBox);
        break;
    default:
        break;
}
CGContextStrokePath(context);
UIImage *backGroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef maskRef = backGroundImage.CGImage;

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), NULL, false);

UIGraphicsBeginImageContext(rect.size);
CGContextRef contextBlack = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(contextBlack, [[UIColor blackColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *blackImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGImageRef masked = CGImageCreateWithMask([blackImage CGImage], mask);
CGImageRelease(mask);
[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageWithCGImage:masked]]];
CGImageRelease(masked);

非常感谢。

【问题讨论】:

    标签: ios5 core-graphics quartz-graphics cgcontext


    【解决方案1】:

    调用UIGraphicsEndImageContext() 会使上下文context 无效。但是,您的程序继续使用该变量。 IOW,你应该在第二次调用UIGraphicsBeginImageContext() 后重新分配context

    context = UIGraphicsGetCurrentContext();
    

    【讨论】:

    • 是的,这解决了问题。复制/粘贴错误。 CGContextFillRect(context, rect);必须是 CGContextFillRect(contextBlack, rect);非常感谢。
    【解决方案2】:

    除了贾斯汀回答:无需将您的代码放在drawRect中。它会被多次调用,你只需要在“形状”改变时重绘你的图案背景。

    调用setShape中的代码

    【讨论】:

    • 但是我必须维护生成图像的副本,不是吗?除此之外,我也这么认为,但 Apple 文档说所有绘图代码都必须在 drawRect 内。我想这不是必需的,甚至可以在后台的另一个线程中创建此图像。你怎么看?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多