为文字贴上不同的纹理图案达到镂空效果。

2017-08-25  本文已影响36人  I_YoYo
背景图片.png 图1.png
图2.png

图1_使用图片做纹理

-(void)test1
{
    CGRect frame = CGRectMake(10, 30, 200, 200);
    CATextLayer *layer = [CATextLayer layer];
    layer.string = @"测试";
    layer.frame = frame;
    layer.fontSize = 60.f;
    layer.contentsScale = [UIScreen mainScreen].scale;
    layer.foregroundColor =[UIColor redColor].CGColor;
    
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageNamed:@"image"];
    imageView.frame = frame;
    imageView.layer.mask = layer;
    [self.view addSubview:imageView];
}

图2_使用渐变做纹理

-(void)test2
{
    CGRect frame = CGRectMake(10, 30, 200, 200);
    CATextLayer *layer = [CATextLayer layer];
    layer.string = @"测试";
    layer.frame = frame;
    layer.fontSize = 60.f;
    layer.contentsScale = [UIScreen mainScreen].scale;
    layer.foregroundColor =[UIColor blackColor].CGColor;
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.startPoint = CGPointMake(0.0, 0.0);
    gradientLayer.endPoint = CGPointMake(1.0,1.0);
    //设置渐变颜色
    NSArray *colors =@[(id)[UIColor redColor].CGColor,(id)[UIColor yellowColor].CGColor,(id)[UIColor greenColor].CGColor,(id)[UIColor blueColor].CGColor];
    gradientLayer.colors = colors;
    NSArray *locations = @[@(0.2f),@(0.4f),@(0.6f),@(0.8f)];
    
    gradientLayer.locations = locations;
    gradientLayer.frame = frame;
    gradientLayer.mask = layer;
    _gradientLayer = gradientLayer;
    [self.view.layer addSublayer:gradientLayer];
}

加个小动画

layer_animation.gif
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"locations";
    NSArray *v1 = @[@(0.1f),@(0.2f),@(0.3f),@(0.8f)];
    NSArray *v2 = @[@(0.4f),@(0.6f),@(0.7f),@(8.0f)];
    NSArray *v3 = @[@(0.1f),@(0.2f),@(0.3f),@(0.8f)];
    animation.values = @[v1,v2,v3];
    animation.duration = 4;
   //重复次数
    animation.repeatCount = 100;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    [_gradientLayer  addAnimation:animation forKey:nil];
    
}

用CATextLayer作为mask,是因为当文字层和图片层叠加在一起,(我想它内部遍历了mask层的每个像素点),把有字的部分(有颜色)抠出作为透明,使其能看地底部图片。
点击下载Demo
有什么错误欢迎批评指正 。

上一篇下一篇

猜你喜欢

热点阅读