想要的效果:
在cocos2dx中有一个遮罩类,ClippingNode.可以很容易的实现文字类遮罩效果,有兴趣的可以自行百度看一看.具体效果图如下.
但是cocos2dx中是用的是openGL实现的效果,直接使用openGL的话会比较难.所以就想着用CALayer的遮罩效果做一个闪烁的标题.
实现原理:
这里用两张一模一样的图片,一张渐变白色,一张是本来的图片,渐变白色是美工PS处理来的.将两张图重叠放在一起,白色在上面,将白色的图片进行遮罩剪切.见效果图.
实现代码:
- (void)viewDidLoad {
[super viewDidLoad];
//添加视图
[self addView];
}
-(void)addView{
//注意Z轴位置
UIImageView *titleBack = [[UIImageView alloc]init];
titleBack.image = [UIImage imageNamed:@"titleBack.png"];
titleBack.frame = CGRectMake(0, 100, SCREEN_SIZE.width, 150);
[self.view addSubview:titleBack];
UIImageView *title = [[UIImageView alloc]init];
title.image = [UIImage imageNamed:@"title.png"];
title.frame = CGRectMake(0, 100, SCREEN_SIZE.width, 150);
[self.view addSubview:title];
//遮罩剪切
title.layer.mask = [self titleMaskLayer:title];
}
-(CALayer*)titleMaskLayer:(UIImageView*)imageView{
//通过图片剪切,也可以自己画一个路径来剪切
CALayer *mask = [CALayer layer];
UIImage *maskImage = [UIImage imageNamed:@"spark.png"];
mask.contents = (__bridge id _Nullable)(maskImage.CGImage);
mask.frame = CGRectMake(100.0f, 0, 50.0f, imageView.bounds.size.height);
mask.bounds = CGRectMake(0, 0, 50.0f, imageView.bounds.size.height);
//添加动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(-50.0f, imageView.bounds.size.height/2.0)];
animation.toValue = [NSValue valueWithCGPoint:CGPointMake(imageView.bounds.size.width, imageView.bounds.size.height/2.0)];
animation.duration = 3.0f;
animation.repeatCount = HUGE_VALF;
[mask addAnimation:animation forKey:@"animation"];
return mask;
}
资源
图片资源在这里,因为很简单就不用上GIT了
总结
通过这个实现原理就可以做很多好玩的东西了,比如像这种注水的加载效果,赶紧用起来吧!