ios中最简单的动画效果,是没有关键帧的,比如左右移动、上下跳动、旋转和缩放。关键帧要稍微复杂一点,要设置路径等。
iOS可以在不借助OpenGL 2D等重型库的情况下实现上述简单的动画效果。编写起来十分简单。
左右移动
上下移动的情况类似。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| - (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation: UIStatusBarAnimationSlide];
UIImage *image=[UIImage imageNamed:@"1.jpg"];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, 768, 1024, 8, 4 * 768, colorSpace, kCGImageAlphaPremultipliedFirst);
CGRect rect = CGRectMake(0, 0, 768, 1024);
CGColorRef fillColor = [[UIColor whiteColor] CGColor];
CGContextSetFillColor(context, CGColorGetComponents(fillColor));
CGContextMoveToPoint(context, 160.0f, 230.0f);
CGContextAddLineToPoint(context, 600.0f, 230.0f);
CGContextAddLineToPoint(context, 600.0f, 100.0f);
CGContextAddLineToPoint(context, 370.0f, 50.0f);
CGContextAddLineToPoint(context, 200.0f, 100.0f);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, rect, image.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *newImage = [UIImage imageWithCGImage:imageMasked];
CGImageRelease(imageMasked);
UIImageView *backView=[[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:backView];
backView.image=newImage;
backView.alpha=0.3;
CABasicAnimation *theAnimation1; //定义动画
//左右摇摆
theAnimation1=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
theAnimation1.fromValue=[NSNumber numberWithFloat:0];
theAnimation1.toValue=[NSNumber numberWithFloat:-100];
theAnimation1.duration=5.5;//动画持续时间
theAnimation1.repeatCount=6;//动画重复次数
theAnimation1.autoreverses=YES;//是否自动重复
[backView.layer addAnimation:theAnimation1 forKey:@"animateLayer"];
[newImage release];
[image release];
} |
旋转
效果类似这样:
这里,图做了pi(180°)的旋转。只需把动画部分代码替换为:
1
2
| theAnimation1=[CABasicAnimation animationWithKeyPath:@"transform"];
theAnimation1.toValue = [ NSValue valueWithCATransform3D: CATransform3DMakeRotation(3.1415, 0, 0, 1.0) ]; |
缩放
缩放类似这样:
代码可替换为:
1
2
| theAnimation1=[CABasicAnimation animationWithKeyPath:@"transform.scale"];
theAnimation1.toValue = [NSNumber numberWithDouble:1.5]; |