Why CGlayerRef or CGcontextRef can't be saved in NSdata?

670 views Asked by At

I saved CGlayerRef and CGcontextRef in NSdata, and when I get them to cover the current one,I find that only the poiners were saved but not the data. For that reason, I can't make these CGlayerRef or CGcontextRef as a copy.(I did this all in drawRect)

Why?some said NSdata could store these things,but NSvalue can not,but ,it dosent work at all, I didnt get the copies of these datas even I used "copy".

Here's my code:

-(void)drawRect:(CGRect)rect{

if (drawCount==3) {

        dataLayer1=[NSData dataWithBytes:& _layerView 

length:sizeof(CGLayerRef)];

   [dataLayer1 retain]; 

               } 



  if (undodo==YES) { 

        _layerView=*(CGLayerRef*)[dataLayer1 bytes]; 



  } 



   currentContext = UIGraphicsGetCurrentContext( ....
2

There are 2 answers

0
jjxtra On

Create your CGLayerRef from a bitmap context and make sure to supply a buffer for the bitmap context. Then when you draw into the layer, your bitmap context backing buffer should contain the new data.

0
Jing On

CGLayer can be saved as NSValue.

if you have successive drawing in a CGLayer and want to part of it, you should

1.copy the CGLayer

- (CGLayerRef)copyLayer:(CGLayerRef)layer
{
    CGSize size = CGLayerGetSize(layer);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGLayerRef copyLayer = CGLayerCreateWithContext(context, size, NULL);
    CGContextRef copyContext = CGLayerGetContext(copyLayer);
    CGContextDrawLayerInRect(copyContext, CGRectMake(0, 0, size.width, size.height), layer);
    UIGraphicsEndImageContext();

    return copyLayer;
}

2.CGLayer to NSValue && NSValue to CGLayer

//CGLayer to NSValue
CGLayerRef copyLayer = [self copyLayer:theLayerYouWantToSave];
NSValue *layerValue = [NSValue valueWithLayer:copyLayer];

//NSValue to CGLayer
theLayerYouWantToRestore = [layerValue layerValue];

3.add category to NSValue

//NSValue category
+ (NSValue *)valueWithLayer:(CGLayerRef)layer
{
    NSValue *value = [NSValue value:&layer withObjCType:@encode(CGLayerRef)];
    return value;
}

- (CGLayerRef)layerValue
{
    CGLayerRef layer;
    [self getValue:&layer];
    return layer;
}