【问题标题】:Why CGlayerRef or CGcontextRef can't be saved in NSdata?为什么 CGlayerRef 或 CGcontextRef 不能保存在 NSdata 中?
【发布时间】:2012-05-31 15:38:44
【问题描述】:

我在 NSdata 中保存了 CGlayerRef 和 CGcontextRef ,当我让它们覆盖当前的时,我发现只保存了指针,而没有保存数据。 因此,我无法将这些 CGlayerRef 或 CGcontextRef 作为副本。(我都是在 drawRect 中完成的)

为什么?有人说 NSdata 可以存储这些东西,但是 NSvalue 不能,但是,它根本不起作用,即使我使用“复制”,我也没有得到这些数据的副本。

这是我的代码:

-(void)drawRect:(CGRect)rect{

如果 (drawCount==3) {

        dataLayer1=[NSData dataWithBytes:& _layerView 

长度:sizeof(CGLayerRef)];

   [dataLayer1 retain]; 

               } 



  if (undodo==YES) { 

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



  } 



   currentContext = UIGraphicsGetCurrentContext( ....

【问题讨论】:

    标签: save nsdata cgcontext cglayer


    【解决方案1】:

    从位图上下文创建 CGLayerRef 并确保为位图上下文提供缓冲区。然后,当您绘制到图层中时,您的位图上下文后备缓冲区应该包含新数据。

    【讨论】:

      【解决方案2】:

      CGLayer 可以保存为 NSValue。

      如果你在一个 CGLayer 中有连续的绘图并想参与其中,你应该

      1.复制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 到 NSValue && NSValue 到 CGLayer

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

      3.添加类别到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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-04
        • 2013-03-03
        相关资源
        最近更新 更多