开发者

Quartz2D how to save the current context and then draw over it?

I'm trying to draw using Quartz2D and but i'm finding the drawing to lag a lot right after a few dots. Therefore I am wondering how can I cach开发者_开发百科e the current context into a bmp or a jpg or a layer and then draw onto the layer again to make the drawing smoother. Which way is the best way to do it? Thanks!


Instead of drawing in a UIView's drawRect and trying to save that drawing layer, you might want to try drawing into a bitmap in a background thread. You never have to clear the bitmap and can just keep drawing into it. Then all you have to do in the UIView drawRect is one image draw of the latest bitmap available, which iOS can do fairly quickly.


IIRC, Quartz2D uses a painting model to render content, and once you draw something you can't interact with it at all, so I don't see why caching the current context would do anything to help.

However, if you want to cache your current context, the code looks something like this:

// Begin image context
UIGraphicsBeginImageContext(view.bounds.size);

[view.layer renderInContext:UIGraphicsGetCurrentContext()];
CGImageRef screenshotRef = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
UIImage *screenshot = [[UIImage alloc] initWithCGImage:screenshotRef];

// End image context
UIGraphicsEndImageContext();
// Release CGImage
CGImageRelease(screenshotRef);

return screenshot;


You can draw one layer to another layer by first converting different layers to images and converge into single Unit.

    //Draw path and return Image
    let firstBeizerPath:UIImage = drawPath(firstBeizerpath: drawCircle())
    let secondBeizerPath:UIImage = drawPath(firstBeizerpath: polygon())

    //Draw different saved context into single image.
    let image = UIImage(). drawOneLayerOverAnother(firstImage:firstBeizerPath , secondImage:secondBeizerPath)

extension UIImage {
    func drawOneLayerOverAnother(firstImage:UIImage , secondImage:UIImage ) -> UIImage {
    UIGraphicsBeginImageContext(firstLayer.size)

    firstImage.draw(in: CGRect(x: 0, y: 0, width: firstLayer.size.width, height: firstLayer.size.height) )
    secondImage.draw(in: CGRect(x: 0, y: 0, width: firstLayer.size.width, height: firstLayer.size.height) )

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
    }
}

Demo App

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜