IOS--CALayer實現,界限、透明度、位置、旋轉、縮放組合動畫(轉)


 


首先引入框架:QuartzCore.framework
在頭文件聲明:CALayer *logoLayer
{
//界限

CABasicAnimation *boundsAnimation = [CABasicAnimationanimationWithKeyPath:@"bounds"];
boundsAnimation.fromValue = [NSValue valueWithCGRect: logoLayer.bounds];
boundsAnimation.toValue = [NSValue valueWithCGRect:CGRectZero];


//透明度變化
CABasicAnimation *opacityAnimation = [CABasicAnimationanimationWithKeyPath:@"opacity"];
opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
opacityAnimation.toValue = [NSNumber numberWithFloat:0.5];
//位置移動

CABasicAnimation *animation  = [CABasicAnimation animationWithKeyPath:@"position"];
animation.fromValue =  [NSValue valueWithCGPoint: logoLayer.position];
CGPoint toPoint = logoLayer.position;
toPoint.x += 180;
animation.toValue = [NSValue valueWithCGPoint:toPoint];
//旋轉動畫
CABasicAnimation* rotationAnimation =
       [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];//"z"還可以是“x”“y”,表示沿z軸旋轉
rotationAnimation.toValue = [NSNumber numberWithFloat:(2 * M_PI) * 3]; 
    // 3 is the number of 360 degree rotations
// Make the rotation animation duration slightly less than the other animations to give it the feel
// that it pauses at its largest scale value
rotationAnimation.duration = 2.0f;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; //緩入緩出


//縮放動畫

CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
scaleAnimation.fromValue = [NSNumber numberWithFloat:0.0];
scaleAnimation.toValue = [NSNumber numberWithFloat:1.0];
scaleAnimation.duration = 2.0f;
scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
animationGroup.duration = 2.0f;
animationGroup.autoreverses = YES;   //是否重播,原動畫的倒播
animationGroup.repeatCount = NSNotFound;//HUGE_VALF;     //HUGE_VALF,源自math.h
[animationGroup setAnimations:[NSArray arrayWithObjects:rotationAnimation, scaleAnimation, nil]];


//將上述兩個動畫編組
[logoLayer addAnimation:animationGroup forKey:@"animationGroup"];
}
//去掉所有動畫
[logoLayer removeAllAnimations];
//去掉key動畫

[logoLayer removeAnimationForKey:@"animationGroup"];

 

 

 

------------------------------------------------------------------------------------------------

 

【學習】iPhone/iOS Core Animation開發總結(CALayer)

轉載自 http://blog.sina.com.cn/s/blog_949e2b3f0101gtxv.html
   

 

一.重要參數

bounds,frame,position屬於基本的幾何定位,相互之間數值變化會相互影響

anchorPoint:單位參數(0-1)表示,變形(transform)時候的變換源點

zPosition:相當於css中z-index的概念,Apple建議不要用這個來替代CALayer層次設置。

cornerRadius:圓角

二.幾何變形(Transforming a Layer's Geometry)

1.用CATransform3D系列方法

        //將CGAffineTransform轉換成CATransform3D

        layer1_1.transform=CATransform3DMakeAffineTransform(CGAffineTransformMakeScale(1, -1));

        //CATransform3D系列方法

        layer1_1.transform=CATransform3DMakeScale(-1, 1, 1);      

        layer1_1.transform=CATransform3DScale(CATransform3DMakeScale(-2, 1, 1), -1, 1, 1);

        layer1_1.transform=CATransform3DIdentity;

 

 

2.修改CATransform3D的data structure

        CATransform3D trans=CATransform3DIdentity;

        NSLog(@"%f",trans.m44);

        //不能是1除以,一定要1.0除以1000(zDistance)

        //wrong     trans.m34=1/100.00

        trans.m34=-1.0/1000;

        trans = CATransform3DTranslate(trans, 0, 0, -240);

        trans = CATransform3DRotate(trans, d2r(90), 1, 0, 0);

        trans = CATransform3DTranslate(trans, 0, 0, 240);

        [layer1 setTransform:trans];

 

 

3.key-valre設置key Paths(rotation,scale,translation)

        [layer1 setValue:[NSNumber numberWithInt:200] forKeyPath:@"transform.translation.x"];

 

 

三.Layer數層結構(Layer-Tree Hierarchy)

1.add,insert,remove,replace來進行樹狀結構的構建

2.重置(Reposition and Resizing)layer

a)你可以通過修改第一點提到的幾個參數來調整大小。

b)needsDisplayOnBoundsChange設置YES,則在bounds變化時,自動調用setNeedsDisplay,調 用layer的display的方法,或者直接顯示調用setNeedsDisplay(不能使用setNeedsDisplayInRect),也會調 用自定義layer的display方法。或者是setNeesLayout,調用layer的layoutSubLayers。(PS:無法使用 layoutManager和autoResizingMask方法,這個是Mac OS上的方法。)

c)在UIView的layoutSubviews里實現自定義layout的方法。

3.masksToBounds設置YES,則裁剪subLayers。否則不裁剪,subLayers可以超過superLayer的bounds。

4.Action

當更改layer的參數或者將layer添加,刪除,隱藏,替換時觸發

觸發方法可以是子類化CALayer,-(id)actionForKey:(NSString*)key;代理方式-(id)actionForLayer:(CALayer*) forKey:(NSString*)key

-(id)actionForLayer:(CALayer *)layer forKey:(NSString *)event{

        CATransition *anim=nil;

        if([event isEqualToString:@"contents"]){

                anim=[CATransition animation];

                anim.duration=2;

                anim.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

                anim.type=@"cube";

                anim.subtype=kCATransitionFromRight;

        }

        return anim;

        //不執行任何動畫

        //return nil;

}

 

 

蘋果文檔種提供了修改sublayers默認動畫的方法

        NSMutableDictionary *cActions=[NSMutableDictionary dictionaryWithDictionary:[layer1_1 actions]];

        [cActions setObject:[NSNull null] forKey:@"sublayers"];

        layer1_1.actions=cActions;

 

 

實現CAAction Protocol

代理類中實現方法runActionForKey:object:arguments

-(void)runActionForKey:(NSString *)event object:(id)anObject arguments:(NSDictionary *)dict{

        NSLog(@"runActionForKey:"%@" object:%@ arguments:%@", event, anObject, dict);

        CATransition *anim=nil;

        if([event isEqualToString:@"test"]){

                anim=[CATransition animation];

                anim.duration=2;

                anim.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

                anim.type=@"cube";

                anim.subtype=kCATransitionFromRight;

        }

 

        [(CALayer*)anObject addAnimation:anim forKey:@"contets"];

}

 

 

觸發runActionForKey

        //添加自定義的action以及對應的觸發方法所在的代理,應該可以定義一個動畫子類(CAAnimation)

        layer1.actions = [NSDictionary dictionaryWithObjectsAndKeys:[[FCLayerDelegate alloc]init], @"test", nil];

        //實際觸發的地方,當設置test參數,其實最后觸發的是runActionForKey種的立方體旋轉

        [layer1 setValue:[NSNumber numberWithInt:19] forKey:@"test"];

 

 

四.提供Layer內容(Providing Layer Content)

1.contents屬性設置CGImageRef

   layer1.contents=(id)image1.CGImage;

 

 

2.用delegate來提供內容

 

a)displayLayer:(CALayer*)

b)-(void)drawLayer:(CALayer*) inContext:(CGContextRef)

//聲明代理

@interface FCLayerDeledegate : NSObject

@end

//實現代理

@implementation FCLayerDelegate

//覆蓋這個方法,就不會執行后面的方法,2者取其一,根據傳入的值來判斷下一步操作

-(void)displayLayer:(CALayer *)layer{

NSLog(@"%@",[layer valueForKey:@"test"]);

}

-(void)drawLayer:(CALayer *)ly inContext:(CGContextRef)context

CGContextSetFillColorWithColor(context, [[UIColor redColor]CGColor]);

CGContextFillRect(context, ly.bounds);

}

@end

 

 

//執行代碼

CALayer* layer1_3=[CALayer layer];        

layer1_3.delegate=[[FCLayerDelegate alloc]init];

[layer1_3 setValue:@"testString" forKey:@"test"];

[layer1_3 setNeedsDisplay];

 

 

ps:以上方法用於CALayer本身(非自己子類)

3) 用子類提供內容

a)display

b)drawInContext:(CGContextRef)

和前面代理模式差不多,只不過少傳layer參數,因為layer就是其本身(self);

4)內容的布局

默認情況下,內容圖片是會鋪開充滿整個layer的bounds的,如果要使得contents按照原來尺寸顯示在layer中,就要設置ContentsGravity

大致2種參數

1.位置參數,注意,ios坐標是y是相反的,所以bottom就是top

2.設置鋪滿方式,3種

layer1_3.contentsGravity=kCAGravityBottomLeft;

layer1_3.contents=(id)image3.CGImage;

//layer1_3.contentsGravity=kCAGravityResizeAspectFill;

 

 

PS:此外contentsCenter這個屬性在鋪滿方式的參數下可以指定拉伸區域,文檔中指出是指定拉伸的范圍,但是似乎沒有作用。暫時忽略。

 

五.動畫

1.動畫類簇

 

a)CAMediaTiming protocol的主要參數

speed:執行速度,如果速度為2,則一個10秒的duration,則只需要5秒完成。子類參數相對父類參數的,如果子類是2,父類是2,則需要2.5秒完成

repeatCount|repeatDuration:重復的次數和重復的間隔 ,如果repeatCount設置成 1e100f則無限重復

fillMode:決定動畫結束時候的狀態。要和removeOnCompletion參數一起設置才有效。動畫結束后的狀態並沒有影響layer的位置,其實layer還在原來的地方沒變。

此外還有duration,autoreverses,beginTime,timeOffset

b)CAAnimation

timingFunction:指定一個CAMediaTimingFunction,有2種提供方式,一種是常量如kCAMediaTimingFunctionLinear,另外一種是自定義2個control points來定制一個時間曲線

functionWithControlPoints::::。

delegate:2個代理方法animationDidStart:和animationDidStop:finished:

2.一般動畫

任何CALayer的animated的屬性或者CTM改變時候都是動畫形式來過渡的,這個稱為implicit Animation。這里不多做介紹

主要介紹下(Explicit Animation)顯示動畫

a)CABasicAnimation 針對某個屬性的設置變化

        CABasicAnimation *anim;

        anim=[CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];

        anim.duration=8;

        anim.autoreverses=NO;

        anim.repeatCount=2;

        anim.fromValue=[NSNumber numberWithFloat:d2r(0)];

        anim.toValue=[NSNumber numberWithFloat:d2r(-90)];

        //  layer1.transform=CATransform3DTranslate(CATransform3DIdentity, 0, 0, 100);

        [layer1 addAnimation:anim forKey:@"layer1Rotation"];

 

 

b)CAKeyframeAnimation

關鍵幀(key frame)有2種方式提供:

參數path,創建CGPathRef

path:CGPathRef 一般用於移動復雜的位置,如下例:

        CGMutablePathRef path=CGPathCreateMutable();

        CGPathMoveToPoint(path, NULL, 40, 420);

        CGPathAddCurveToPoint(path, NULL, 40, 40, 160, 40, 160, 420);

        CGPathAddCurveToPoint(path, NULL, 160, 40, 280, 40, 280, 420);

        CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"position"];

        anim.path=path;

        anim.duration=3;

        

        //圖像在移動過程中是否旋轉

        anim.rotationMode=kCAAnimationRotateAuto;

        //動畫結束時候狀態,我動畫結束在哪里就停在哪里

        anim.removedOnCompletion = NO;

        anim.fillMode=kCAFillModeForwards;

        //設置keyTimes path加了2個點,所以將duration設置成了2段,前面一段快3/10,后面一段慢7/10

        anim.calculationMode=kCAAnimationLinear;

        anim.keyTimes=[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],[NSNumber numberWithFloat:0.3],[NSNumber numberWithFloat:1.0], nil];

        [layer1 addAnimation:anim forKey:@"nm1"];

        CGPathRelease(path);

 

 

參數values:array of objects

如果objects是CGImage,key-path是"contents"的話,則是圖像切換。

        CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"contents"];

        anim.duration=3;

        anim.values=[NSArray arrayWithObjects:(id)image1.CGImage,(id)image2.CGImage,(id)image3.CGImage,nil];

        [layer1 addAnimation:anim forKey:@"nm2"];

 

 

如果objects是CATransform3D的,key-path是“transform”,則是變換坐標

        CAKeyframeAnimation *anim2=[CAKeyframeAnimation animationWithKeyPath:@"transform"];

        anim2.duration=3;

        anim2.repeatCount=1000;

        anim2.autoreverses=YES;

        CATransform3D trans=CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1);

        CATransform3D trans2=CATransform3DScale(CATransform3DIdentity, 1, 1, 1);

        anim2.values=[NSArray arrayWithObjects:[NSValue valueWithCATransform3D:trans],[NSValue valueWithCATransform3D:trans2],nil];

        [layer1 addAnimation:anim2 forKey:@"nm3"];

 

 

如果2個同時設置,還可以同時看到動畫效果。比方說上述2個就可以看到圖片切換並且放大和縮小的效果。

不要針對frame和size等參數設置keyframe動畫,似乎沒有效果。position是可以的。

3.動畫事務(Transaction)

        [CATransaction begin];

        [CATransaction setValue:[NSNumber numberWithFloat:.5f] forKey:kCATransactionAnimationDuration];

        layer1.position=CGPointMake(0, 0);

        layer1.opacity=0;

        [CATransaction commit];

 

 

通過事務可以修改implicit 動畫的時間,否則沒有辦法修改。

4.動畫過渡(Transition)

        //CATransition

        CATransition *animation = [CATransition animation];

        animation.delegate = self;

        animation.duration = 2;

        animation.timingFunction = UIViewAnimationCurveEaseInOut;

        //animation.type = kCATransitionFade;

        animation.type = @"cube";

        animation.subtype = kCATransitionFromLeft;

        //2個view交換

        NSUInteger green = [[self.view subviews] indexOfObject:self.greenView];

        NSUInteger blue = [[self.view subviews] indexOfObject:self.blueView];

        [self.view exchangeSubviewAtIndex:green withSubviewAtIndex:blue];

        [layer1 addAnimation:animation forKey:@"animation"];

 

 

過渡有view的過渡和layer的過渡,2者是有區別的,網上有個例子transition包含了一共12種變換,相當有用。

參考文檔:

Animation Types and Timing Programming Guide

Core Animation Programming Guide

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM