UIView:如何进行无损绘图? [英] UIView: how to do non-destructive drawing?

查看:15
本文介绍了UIView:如何进行无损绘图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原来的问题:

我正在创建一个简单的绘图应用程序并且需要能够在我的 drawRect 中绘制现有的、以前绘制的内容.在现有内容之上绘制的正确方法是什么没有完全取代它?

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?

根据此处和其他地方收到的答案,交易如下.

Based on answers received here and elsewhere, here is the deal.

  1. 你应该准备好重新绘制每当 drawRect 时,整个矩形叫做.

不能通过执行以下操作来防止内容被删除:

You cannot prevent the contents from being erased by doing the following:

[self setClearsContextBeforeDrawing: NO];

这只是对图形引擎的一个提示,让它为您预先清除视图是没有意义的,因为无论如何您可能需要重新绘制整个区域.它可能会阻止您的视图被自动删除,但您不能依赖它.

This is merely a hint to the graphics engine that there is no point in having it pre-clear the view for you, since you will likely need to re-draw the whole area anyway. It may prevent your view from being automatically erased, but you cannot depend on it.

要在不擦除的情况下在视图顶部绘制,请在屏幕外位图上下文(系统永远不会清除)中进行绘制.然后在您的 drawRect 中,从这个屏幕外缓冲区到视图.

To draw on top of your view without erasing, do your drawing to an off-screen bitmap context (which is never cleared by the system.) Then in your drawRect, copy from this off-screen buffer to the view.

示例:

- (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 以便只有(通常很小的)修改后的矩形区域用于复制?

TODO: can anyone optimize the drawRect so that only the (usually tiny) modified rectangle region is used for the copy?

推荐答案

在离屏图像中绘制所有内容并在绘制屏幕时简单地显示此图像是相当普遍的.您可以阅读:创建位图图形上下文.

It is fairly common to draw everything in an offscreen image, and simply display this image when drawing the screen. You can read: Creating a Bitmap Graphics Context.

这篇关于UIView:如何进行无损绘图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆