How to render to offscreen bitmap then blit to screen using Core Graphics

前端 未结 4 1838
有刺的猬
有刺的猬 2020-12-15 19:51

I would like to render to an offscreen bitmap (or array of RGBA values) and then blit those to a UIView during in the view\'s drawRect function. I

4条回答
  •  清酒与你
    2020-12-15 20:47

    To render into an offscreen context and save it as a CGImageRef:

    void *bitmapData = calloc(height, bytesPerLine);
    CGContextRef offscreen = CGBitmapContextCreate(..., bitmapData, ...)
    // draw stuff into offscreen
    CGImageRef image = CGBitmapContextCreateImage(offscreen);
    CFRelease(offscreen);
    free(bitmapData);
    

    To draw it on the screen:

    - (void)drawRect:(CGRect)rect {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextDrawImage(context, rect, image);
    }
    

    You could also just save the image in the view's layer's contents property (view.layer.contents = image), or use a UIImageView.

提交回复
热议问题