drawRect圆和动画大小/颜色

Sko*_*ota 29 core-animation quartz-graphics ios ios5

我在使用标准代码的-drawRect:方法中画了一个圆圈.但是,我想略微脉冲(变大和变小)并用动画改变颜色填充的强度.例如,如果圆圈充满了红色,我想用脉冲圆圈,并使脉冲动作使红色稍微更轻,更暗.没有太多的核心动画经验我对如何做到这一点有点迷茫,所以任何帮助将不胜感激.UIViewCGContextFillEllipseInRect()

rob*_*off 71

如果你不画圆圈,这会简单得多drawRect:.相反,将视图设置为使用a CAShapeLayer,如下所示:

@implementation PulseView

+ (Class)layerClass {
    return [CAShapeLayer class];
}
Run Code Online (Sandbox Code Playgroud)

layoutSubviews无论何时更改大小(包括首次出现时),系统都会发送到您的视图.我们覆盖layoutSubviews以设置形状并为其设置动画:

- (void)layoutSubviews {
    [self setLayerProperties];
    [self attachAnimations];
}
Run Code Online (Sandbox Code Playgroud)

以下是我们如何设置图层的路径(确定其形状)和形状的填充颜色:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

我们需要在图层上附加两个动画 - 一个用于路径,另一个用于填充颜色:

- (void)attachAnimations {
    [self attachPathAnimation];
    [self attachColorAnimation];
}
Run Code Online (Sandbox Code Playgroud)

以下是我们为图层路径设置动画的方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

以下是我们为图层的填充颜色设置动画的方法:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

这两种attach*Animation方法都使用辅助方法创建基本动画并将其设置为使用自动反转和一秒持续时间无限重复:

- (CABasicAnimation *)animationWithKeyPath:(NSString *)keyPath {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath];
    animation.autoreverses = YES;
    animation.repeatCount = HUGE_VALF;
    animation.duration = 1;
    return animation;
}
Run Code Online (Sandbox Code Playgroud)

  • `PulseView`是`UIView`的子类. (4认同)