面试题答案
一键面试- 引入框架:
在使用Core Animation框架之前,需要在项目中引入
QuartzCore.framework
,并且在源文件中导入头文件:
#import <QuartzCore/QuartzCore.h>
- 创建动画对象:
使用
CABasicAnimation
类来创建淡入淡出动画。淡入淡出动画主要是改变视图的opacity
属性。
CABasicAnimation *fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
- 设置动画属性:
- 淡入动画:
将
fromValue
设置为0(完全透明),toValue
设置为1(完全不透明)。
fadeAnimation.fromValue = @0;
fadeAnimation.toValue = @1;
- 淡出动画:
将
fromValue
设置为1(完全不透明),toValue
设置为0(完全透明)。
fadeAnimation.fromValue = @1;
fadeAnimation.toValue = @0;
同时,还可以设置动画的持续时间、重复次数等其他属性。例如,设置动画持续时间为2秒:
fadeAnimation.duration = 2.0;
- 添加动画到视图的图层:
获取视图的图层,然后将动画添加到图层上。假设视图为
aView
:
CALayer *viewLayer = aView.layer;
[viewLayer addAnimation:fadeAnimation forKey:@"fadeAnimation"];
- 完整代码示例(淡入动画):
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface ViewController : UIViewController
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
aView.backgroundColor = [UIColor redColor];
[self.view addSubview:aView];
CABasicAnimation *fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnimation.fromValue = @0;
fadeAnimation.toValue = @1;
fadeAnimation.duration = 2.0;
CALayer *viewLayer = aView.layer;
[viewLayer addAnimation:fadeAnimation forKey:@"fadeAnimation"];
}
@end
- 完整代码示例(淡出动画):
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface ViewController : UIViewController
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
aView.backgroundColor = [UIColor redColor];
[self.view addSubview:aView];
CABasicAnimation *fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnimation.fromValue = @1;
fadeAnimation.toValue = @0;
fadeAnimation.duration = 2.0;
CALayer *viewLayer = aView.layer;
[viewLayer addAnimation:fadeAnimation forKey:@"fadeAnimation"];
}
@end