如果你不在drawRect: 中画圆,这会简单得多。相反,请将您的视图设置为使用CAShapeLayer,如下所示:
@implementation PulseView
+ (Class)layerClass {
return [CAShapeLayer class];
}
当layoutSubviews 大小发生变化时(包括首次出现时),系统会将layoutSubviews 发送到您的视图。我们覆盖layoutSubviews 来设置形状并为其设置动画:
- (void)layoutSubviews {
[self setLayerProperties];
[self attachAnimations];
}
以下是我们如何设置图层的路径(决定其形状)和形状的填充颜色:
- (void)setLayerProperties {
CAShapeLayer *layer = (CAShapeLayer *)self.layer;
layer.path = [UIBezierPath bezierPathWithOvalInRect:self.bounds].CGPath;
layer.fillColor = [UIColor colorWithHue:0 saturation:1 brightness:.8 alpha:1].CGColor;
}
我们需要给图层附加两个动画——一个用于路径,一个用于填充颜色:
- (void)attachAnimations {
[self attachPathAnimation];
[self attachColorAnimation];
}
以下是我们为图层路径设置动画的方式:
- (void)attachPathAnimation {
CABasicAnimation *animation = [self animationWithKeyPath:@"path"];
animation.toValue = (__bridge id)[UIBezierPath bezierPathWithOvalInRect:CGRectInset(self.bounds, 4, 4)].CGPath;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.layer addAnimation:animation forKey:animation.keyPath];
}
下面是我们如何为图层的填充颜色设置动画:
- (void)attachColorAnimation {
CABasicAnimation *animation = [self animationWithKeyPath:@"fillColor"];
animation.fromValue = (__bridge id)[UIColor colorWithHue:0 saturation:.9 brightness:.9 alpha:1].CGColor;
[self.layer addAnimation:animation forKey:animation.keyPath];
}
attach*Animation 的两个方法都使用了一个辅助方法,该方法创建一个基本动画并将其设置为无限重复,自动反转和一秒的持续时间:
- (CABasicAnimation *)animationWithKeyPath:(NSString *)keyPath {
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
animation.autoreverses = YES;
animation.repeatCount = HUGE_VALF;
animation.duration = 1;
return animation;
}