質問

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.

役に立ちましたか?

解決

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.

他のヒント

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top