0

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.

PDaria
  • 457
  • 10
  • 21
  • 1
    Why do you need to create it outside of drawRect? The CGContext that gets passed to CGLayer is just a reference you know, it doesn't use that exact one. It just models its own context after it. – borrrden Jun 27 '12 at 01:43
  • 1
    Everybody does it on the first drawRect call as far as I know. It might even be the only way. That's the way I do it. It's more resilient because it will work even if you change the view properties. – borrrden Jun 27 '12 at 04:36
  • Thank you! Maybe you better post the answer and I check it as correct? – PDaria Jun 27 '12 at 06:23

2 Answers2

0

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.

borrrden
  • 33,256
  • 8
  • 74
  • 109
  • 1
    "no reason" - well ... IME, Apple freezes iOS's entire render stack, except for CoreAnimation (i.e. you lose control over everything, except for CA's that you triggered before it started), once it drops into a drawRect call (i.e. drawRect's are treated as an atomic operation, no matter how complex they are). That's a pretty big reason to avoid rendering inside drawRect, if you can. (some things simply take a long time to render - Quartz on iOS is quite weak (I use it a lot, but some calls are orders of magnitude slower than on OS X)) – Adam Mar 02 '13 at 20:57
0

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

Hao
  • 201
  • 1
  • 3