UIView: how to do non-destructive drawing?

前端 未结 4 633
[愿得一人]
[愿得一人] 2020-12-08 08:03

My original question:

I\'m creating a simple drawing application and need to be able to draw over existing, previously drawn content in my d

相关标签:
4条回答
  • 2020-12-08 08:54

    On optimizing drawRect

    Try this:

    - (void)drawRect:(CGRect)rect {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGImageRef cgImage = CGBitmapContextCreateImage(drawingContext);
        CGContextClipToRect(context, rect);
        CGContextDrawImage(context, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height), cgImage);
        CGImageRelease(cgImage);
    }
    

    After that you should also comment these lines in your code:

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

    Also created a separate question to be sure that it's the optimal way.

    0 讨论(0)
  • 2020-12-08 08:54

    This prevents your view from being erased before drawRect is done:

    [self.layer setNeedsDisplay];
    

    Also, I find it is better to do all the drawing in the drawRect method (unless you have a good reason not to). Drawing offscreen and transferring takes more time and adds more complexity then simply drawing everything once.

    0 讨论(0)
  • 2020-12-08 08:57

    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.

    0 讨论(0)
  • 2020-12-08 08:58

    This seems like a better method than I've been using. That is, in a touches event I make a copy of the view about to be updated. Then in drawRect I take that image and draw it to the view and make my other view changes at the same time.

    But this seems inefficient but the only way I figured out how to do it.

    0 讨论(0)
提交回复
热议问题