zoukankan      html  css  js  c++  java
  • iOS CALayer应用详解(2)

    参考博客:http://blog.csdn.net/hello_hwc?viewmode=list

    如果你对CALayer 还没有一个清晰的理解,欢迎看一下前面的博客:

    http://www.cnblogs.com/huanying2000/p/6244673.html

    如果你对Layer有一定的了解 请直接看下面的文章

    一 提供CALayer内容的单中方式

    1>把一个图像对象直接赋值给contents属性(这是提供CALayer内容的最好方式)

    2>设置delegate,让代理绘制layer的内容

    3>继承CALayer 重写绘制方法 来提供layer的内容

    由于上面讲了利用contents给layer提供内容 这里就不写了

    http://www.cnblogs.com/huanying2000/p/6244673.html

    通过设置delegate 提供内容

    举例

    使用displayLayer来实现

    @interface ProvideLayerContentsVC()  
    @property (strong,nonatomic)CALayer * sublayer;  
    @property (strong,nonatomic)NSTimer * timer;  
    @property (nonatomic)NSUInteger  randomState;  
    @end  
      
    @implementation ProvideLayerContentsVC  
      
    -(CALayer *)sublayer{  
        if (!_sublayer) {  
            _sublayer = [CALayer layer];  
            _sublayer.position = self.view.center;  
            _sublayer.bounds = CGRectMake(0,0,200,200);  
            [self.view.layer addSublayer:_sublayer];  
        }  
        return _sublayer;  
    }  
    -(NSUInteger)randomState{  
        _randomState = arc4random()%5+1;  
        return _randomState;  
    }  
    -(void)viewWillAppear:(BOOL)animated  
    {  
        self.sublayer.delegate = self;  
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self.sublayer selector:@selector(setNeedsDisplay) userInfo:nil repeats:YES];  
    }  
    -(void)displayLayer:(CALayer *)layer  
    {  
        NSString * imageName = [NSString stringWithFormat:@"image%lu.jpg",(unsigned long)self.randomState];  
        layer.contents = (id)[UIImage imageNamed:imageName].CGImage;  
    }  
    @end  

    这段代码的的功能是每隔一秒钟,随机更换layer的图片

    使用draw:inContext实现自定义重新绘制

    -(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{  
        CGMutablePathRef path = CGPathCreateMutable();  
        CGPathAddArc(path,NULL,100,100,95,0,M_PI*2, YES);  
        CGContextBeginPath(ctx);  
        CGContextAddPath(ctx,path);  
        CGContextSetLineWidth(ctx, 5);  
        CGContextStrokePath(ctx);  
        CFRelease(path);  
    }  

    二 Layer Tree
    Layer Tree分为三种,Model Layer Tree,Presentation Tree,Render Tree
    其中,Render Tree为CoreAnimation私有的,是CoreAnimation具体实现使用的私有Tree,这里不做讨论。
    Model Layer Tree:存储的是模态对象,也是我们通常处理的对象,比如layer.position = CGPointMake(10.0,10.0)修改的就是Model Layer Tree
    Presentation Tree:存储的是正在执行的动画的当前状态,是个动态的树,由这个树来获取当前动画运行到哪里。
    这两点对后续Core Animation的深入理解很重要。
    上述三种Tree的对应关系如下图

  • 相关阅读:
    61. 最长不含重复字符的子字符串
    60. 礼物的最大价值 (未理解)
    59. 把数字翻译成字符串
    58. 把数组排成最小的数
    57. 数字序列中某一位的数字 (不懂)
    spring data jpa 官方文档
    idea 编译报错 源发行版 1.8 需要目标发行版 1.8
    idea maven 依赖报错 invalid classes root
    solr
    spring boot 官方文档
  • 原文地址:https://www.cnblogs.com/huanying2000/p/6244735.html
Copyright © 2011-2022 走看看