CALayer层和CAAnimation动画

每一个ViewController默认有一个UIView,可以自定义UIView加入到ViewController默认的的视图中。也可以有子视图加入到视图中。

每一个UIView视图中又有一个默认的CALayer对象,就是层的概念。当然,也可以定义自己的CALayer,加入到UIView的默认的层中

@interface GraphicsView : UIView {
    CALayer *imageLayer;
}

@end

在一个自定义的视图GraphicsView中加入一个CALayer对象imageLayer,因为在这个层中我们显示一幅图片。

在GraphicsView的init方法中,我们写入一下:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        UIImage *image = [UIImage imageNamed:@"LRY.jpg"];
        CGImageRef cgImage = [image CGImage];

        imageLayer = [[CALayer alloc]init];
        [imageLayer setBounds:CGRectMake(0.0, 0.0, 200.0, 200.0)];
        [imageLayer setPosition:CGPointMake(160.0, 100.0)];
        
        UIColor *reddish = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:0.1];
        CGColorRef cgReddish = [reddish CGColor];
        [imageLayer setBackgroundColor:cgReddish];
        imageLayer.contents = (id)cgImage;
        [[self layer]addSublayer:imageLayer];
        self.backgroundColor = [UIColor grayColor];
        
    }
    return self;
}
层中的图片不能直接用UIImage,要转为CGImage,很好转的。。设置imageLayer的大小和位置,同样层中也不能用UIColor,要用CGColor代替,

同样好转。我只直接设置层的内容,contents为图像,直接可以显示,方便。。


CALayer层的很多属性都是隐式可动画的,像position,center,alpha等,就是说,如果把层的中心从一个点编程另外的点,是带动画的。

我们可以空CAAnimation中的方法,产生动画

- (void)drawRect:(CGRect)rect
{

    //CABasicAnimation改变CALayer的opacity(透明度)动画。
    CABasicAnimation *fader = [CABasicAnimation animationWithKeyPath:@"opacity"];
    [fader setDuration:2.0];
    [fader setRepeatCount:10];
    [fader setFromValue:[NSNumber numberWithFloat:1.0]];
    [fader setToValue:[NSNumber numberWithFloat:0.0]];
    [imageLayer addAnimation:fader forKey:@"BigFire"];
}
或者:
- (void)drawRect:(CGRect)rect
{
    //CABasicAnimation改变位置的动画,CABasicAnimation只能让CALyaer属性从一个值编程另外一个值
    CABasicAnimation *mover = [CABasicAnimation animationWithKeyPath:@"position"];
    [mover setDuration:1.0];
    [mover setFromValue:[NSValue valueWithCGPoint:CGPointMake(0.0, 100.0)]];
    [mover setFromValue:[NSValue valueWithCGPoint:CGPointMake(100.0, 100.0)]];
    [imageLayer addAnimation:mover forKey:@"move"];
    
    //CAKeyFrameAnimation没有限制,可以从一个值变为一个值,然后再变,加载成一个数组。
    CAKeyframeAnimation *keyFrameMover = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    NSMutableArray *vals = [NSMutableArray array];
    [vals addObject:[NSValue valueWithCGPoint:CGPointMake(0.0, 100.0)]];
    [vals addObject:[NSValue valueWithCGPoint:CGPointMake(300.0, 300.0)]];
    [vals addObject:[NSValue valueWithCGPoint:CGPointMake(0.0, 0.0)]];
    [keyFrameMover setValues:vals];
    [keyFrameMover setDuration:4.0];
    [imageLayer addAnimation:keyFrameMover forKey:@"KeyFrameMover"];

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值