UIView:如何进行非破坏性绘图? [英] UIView: how to do non-destructive drawing?

查看:211
本文介绍了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 整个矩形$ c>
    被调用。

  1. You should be prepared to redraw the entire rectangle whenever drawRect is called.

无法通过执行以下操作来阻止内容被删除:

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天全站免登陆