《ios核心动画高级技巧》阅读笔记(3)

第四章 视觉效果

圆角

  • 设置CALayer的cornerRadius属性来设置圆角,并且要把maskToBounds设置为YES

边框

  • 设置CALayer的borderColor和borderWidth可以设置边框的颜色和宽度

阴影

  • shadowColor:阴影的颜色
  • shadowOpacity:阴影的透明度
  • shadowOffset:阴影的偏移
  • shadowRadius:阴影的模糊度,即模糊半径
  • 如果设置了maskToBounds,则阴影就不会显示了,因为阴影已经被裁减调了。要解决这个问题,可以再创建一个frame一样的View,给这个view设置阴影,而设置原本的view的maskToBounds,这样阴影就不会被裁减掉了。
  • shadowPath:指定阴影的路径。
  • 设置ImageView,label等的阴影,并不是设置他们边界的阴影,而是设置里面内容的阴影,例如设置label的阴影,设置的是label中文字的阴影。
1
2
3
4
5
6
7
8
9
10
11
12
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.buleView.hidden = YES;
self.layerView.layer.shadowColor = [UIColor redColor].CGColor;
self.layerView.layer.shadowOpacity = 1;
self.layerView.layer.shadowRadius = 10;

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, self.layerView.bounds);
self.layerView.layer.shadowPath = path;
CGPathRelease(path);
}

图层蒙版

  • mask:CALayer的mask属性定义了父图层的部分可见区域,父图层与mask的关系如下图

mask

  • 虽然设置了mask,但是视图的事件响应区域任然是原视图的区域
  • mask是可以动态设置的,只要改变mask的大小,就可以对视图的显示区域进行动画
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
CAShapeLayer *mask = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:self.greenBtn.bounds];
mask.path = path.CGPath;
self.greenBtn.layer.mask = mask;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

UIBezierPath *endPath = [UIBezierPath bezierPathWithRect:self.greenBtn.bounds];
CAShapeLayer *layer = (CAShapeLayer *)self.greenBtn.layer.mask;

// 动画
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
animation.duration = 1;
animation.fromValue = (id)layer.path;
animation.toValue = (__bridge id _Nullable)(endPath.CGPath);
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
[layer addAnimation:animation forKey:@"shapeLayerPath"];
}

拉伸过滤

  • minificationFilter:缩小图片的拉伸算法
  • magnificationFilter:方法图片的拉伸算法
  • 三个值:kCAFilterNearest,kCAFilterLinear,kCAFilterTrilinear

组透明

  • 改变视图或图层的透明度,其子视图或子图层的透明度也会跟着改变,但是经过叠加后,原本颜色相同的父子视图,变成了不同的视图,如下图:

group-opacity

  • 为了解决这种问题,可以在plist中添加”Renders with group opacity”为YES(目前ios9中默认就为YES),或者设置CALayer的shouldRasterize为YES也可以达到相同的效果。