CALayer遮罩层动画

时间:2019-01-26 14:31:42

标签: uikit core-animation calayer cashapelayer

我想用另一层遮罩CALayer,我想在每个绘制调用中不断更改其帧从而进行动画处理。是否可以在每个绘制调用中更改遮罩层的框架,而不是制作新的遮罩层?

1 个答案:

答案 0 :(得分:0)

尝试以下代码。此代码将在适用于macOS的Cocoa App上运行。如果要使用iOS的Cocoa Touch,请相应地更改类。希望这对您有用。

// ViewController.h

导入

@interface ViewController:NSViewController {

CALayer * maskLayer;
CALayer * Layer;   

}

// ViewController.m

@implementation ViewController

-(void)viewDidLoad {

[super viewDidLoad];

maskLayer = [CALayer layer];
Layer = [CALayer layer];

Layer.backgroundColor = [[NSColor blueColor] CGColor];
Layer.frame = CGRectMake(20, 20, 720, 900);
Layer.contents = [NSImage imageNamed:@"bg1"];

maskLayer.frame = CGRectMake(20, 20, 720, 900);
maskLayer.opacity = 0.5;
[maskLayer mask];

maskLayer.contents = [NSImage imageNamed:@"bg"];


[self.view.layer addSublayer:Layer];
[self.view.layer addSublayer:maskLayer];

[self maskLayerAnimation];

}

-(void)maskLayerAnimation {

[CATransaction begin];
CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnim.fromValue = [NSNumber numberWithFloat:1.0];
fadeAnim.toValue = [NSNumber numberWithFloat:0.0];
fadeAnim.duration = 5.0;


[CATransaction setCompletionBlock:^{
    NSLog(@"animation completed");
    maskLayer.frame = CGRectMake(20, 20, 720, 700);
    maskLayer.contents = [NSImage imageNamed:@"bg2"];
}];;

[maskLayer addAnimation:fadeAnim forKey:@"opacity"];
[CATransaction commit];

}