的drawRect圆和动画大小/颜色(drawRect circle and animate siz

2019-06-24 23:41发布

我画的一个圆圈-drawRect:我的方法UIView使用标准CGContextFillEllipseInRect()代码。 然而,我想稍微脉冲(使更大和更小),并改变颜色的强度填充的动画。 例如,如果圈充满了红色,我想脉圈,使红色稍轻,并及时与较深的脉冲作用。 由于没有与核心动画太多的经验我有点失去了关于如何做到这一点,所以任何帮助将不胜感激。

Answer 1:

这是简单得多,如果你不画在圈内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;
}


文章来源: drawRect circle and animate size/color