原创Blog,转载请注明出处
blog.csdn.net/hello_hwc
不了解CALayer基础的同学,建议先看看前一篇CALayer详解(一)
http://blog.csdn.net/hello_hwc/article/details/42580773
前言:本文涵盖了(1)绘制CALayer的三种方式(2)Layer Tree
一 提供CALayer内容的三种方式
@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的图片。效果如下
-(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); }效果如下