Create CGContext for CGLayer

99封情书 提交于 2019-12-13 03:36:32

问题


I want to pre-render some graphics into CGLayer for fast drawing in future.

I found that CGLayerCreateWithContext requires a CGContext parameter. It can be easily found in drawRect: method. But I need to create a CGLayer outside of drawRect:. Where should I get CGContext?

Should I simply create temporary CGBitmapContext and use it?

UPDATE: I need to create CGLayer outside of drawRect: because I want to initialize CGLayer before it is rendered. It is possible to init once on first drawRect call but it's not beautiful solution for me.


回答1:


There is no reason to do it outside of drawRect: and in fact there are some benefits to doing it inside. For example, if you change the size of the view the layer will still get made with the correct size (assuming it is based on your view's graphics context and not just an arbitrary size). This is a common practice, and I don't think there will be a benefit to creating it outside. The bulk of the CPU cycles will be spent in CGContextDrawLayer anyway.




回答2:


You can create it by this function, you can render your content in the render block

typedef void (^render_block_t)(CGContextRef);

- (CGLayerRef)rendLayer:(render_block_t) block {
    UIGraphicsBeginImageContext(CGSizeMake(100, 100));
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGLayerRef cgLayer = CGLayerCreateWithContext(context, CGSizeMake(100, 100), nil);
    block(CGLayerGetContext(cgLayer));
    UIGraphicsEndImageContext();
    return cgLayer;
}

I wrote it few days ago. I use it to draw some UIImages in mutable threads. You can download the code on https://github.com/PengHao/GLImageView/ the file path is GLImageView/GLImageView/ImagesView.m



来源:https://stackoverflow.com/questions/11207801/create-cgcontext-for-cglayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!