Ví dụ đơn giản làm việc:
tập tin .h
@property (strong, nonatomic) CAGradientLayer *gradient;
tập tin .m
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear: animated];
self.gradient = [CAGradientLayer layer];
self.gradient.frame = self.view.bounds;
self.gradient.colors = @[(id)[UIColor purpleColor].CGColor,
(id)[UIColor redColor].CGColor];
[self.view.layer insertSublayer:self.gradient atIndex:0];
[self animateLayer];
}
-(void)animateLayer
{
NSArray *fromColors = self.gradient.colors;
NSArray *toColors = @[(id)[UIColor redColor].CGColor,
(id)[UIColor orangeColor].CGColor];
[self.gradient setColors:toColors];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"colors"];
animation.fromValue = fromColors;
animation.toValue = toColors;
animation.duration = 3.00;
animation.removedOnCompletion = YES;
animation.fillMode = kCAFillModeForwards;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.delegate = self;
// Add the animation to our layer
[self.gradient addAnimation:animation forKey:@"animateGradient"];
}
Bạn có thể muốn thực hiện một phương pháp bổ sung để chuyển màu sắc, và sau đó reanimate những thay đổi . Nhưng điều này sẽ giúp bạn đạt được điều đó.
Cách thức và địa điểm sẽ triển khai 3b ở đâu? –
3b đã cung cấp cho bạn một hoạt ảnh trong một thời hạn nhất định; vì vậy bạn chỉ cần gói nó vào một phương thức và gọi nó (ví dụ: từ viewDidLoad); bạn cần sau đó cung cấp một cơ chế để nó được lặp lại sau 'duration' giây; cho rằng bạn có thể sử dụng bộ hẹn giờ hoặc sử dụng khối 'hoàn thành' cho hoạt ảnh. Tôi đã mở rộng câu trả lời của mình để tính đến điều này. – sergio
Mã này, khi được triển khai như bạn đã nói có một số lỗi: Sử dụng số nhận dạng không khai báo, topColor; Thuộc tính 'giới hạn' không được tìm thấy trên loại đối tượng "Xem trình điều khiển *" chẳng hạn. –