drawRect圆和动画大小/颜色

时间:2012-05-30 02:34:55

标签: ios ios5 core-animation quartz-graphics

我正在使用标准-drawRect:代码在我的UIView CGContextFillEllipseInRect()方法中绘制一个圆圈。但是,我想略微脉冲(变大和变小)并用动画改变颜色填充的强度。例如,如果圆圈充满了红色,我想用脉冲圆圈,并使脉冲动作的红色稍微更亮更暗。没有太多关于Core Animation的经验我对如何做到这一点有点失落,所以任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:71)

如果不在drawRect:中绘制圆圈,这会更简单。相反,请将视图设置为使用CAShapeLayer,如下所示:

@implementation PulseView

+ (Class)layerClass {
    return [CAShapeLayer class];
}

只要系统更改大小(包括首次显示时),系统就会向您的视图发送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;
}