iphone – UIView:怎么做非破坏性绘图?

我原来的问题:

I’m creating a simple drawing
application and need to be able to
draw over existing, previously drawn content in my drawRect.
What is the proper way to draw on top of existing content
without entirely replacing it?

根据这里和其他地方收到的答复,这里是交易.

>你应该准备重画
整个矩形每当drawRect
叫做.
>您不能通过执行以下操作来防止内容被擦除:

[self setClearsContextBeforeDrawing:NO];

这只是对图形引擎的一个暗示,因为您可能需要重新绘制整个区域,因此无需为您预先清除视图.它可能会阻止您的视图被自动删除,但您不能依赖它.
>要绘制在您的视图顶部而不擦除,请将绘图移至屏幕外的位图上下文(这不会被系统清除).然后在您的drawRect中,从该屏幕外缓冲区复制到视图.

例:

- (id) initWithCoder: (NSCoder*) coder {    
     if (self = [super initWithCoder: coder]) {
         self.backgroundColor = [UIColor clearColor];
         CGSize size = self.frame.size;
         drawingContext = [self createDrawingBufferContext: size];
     }

     return self;
 }

- (CGContextRef) createOffscreenContext: (CGSize) size  {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaPremultipliedLast);
    CGColorSpaceRelease(colorSpace);

    CGContextTranslateCTM(context, 0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    return context;
}


- (void)drawRect:(CGRect) rect {    
    UIGraphicsPushContext(drawingContext);
    CGImageRef cgImage = CGBitmapContextCreateImage(drawingContext); 
    UIImage *uiImage = [[UIImage alloc] initWithCGImage:cgImage];
    UIGraphicsPopContext();
    CGImageRelease(cgImage);
    [uiImage drawInRect: rect];
    [uiImage release];
 }

TODO:任何人都可以优化drawRect,以便只有(通常是微小的)修改的矩形区域用于副本?

在屏幕外的图像中绘制所有内容是相当普遍的,只需在绘制屏幕时显示此图像.您可以阅读:Creating a Bitmap Graphics Context.
翻译自:https://stackoverflow.com/questions/865636/uiview-how-to-do-non-destructive-drawing

转载注明原文:iphone – UIView:怎么做非破坏性绘图?