【问题标题】:drawRect circle and animate size/colordrawRect 圆和动画大小/颜色
【发布时间】:2012-05-30 02:34:55
【问题描述】:

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

【问题讨论】:

    标签: ios ios5 core-animation quartz-graphics


    【解决方案1】:

    如果你不在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;
    }
    

    【讨论】:

    • 很棒的解释。非常感谢:)
    • 这正是我正在寻找的,但我如何从 UIView 调用它以使其出现?我假设这段代码是在它自己的类中设置的。
    • PulseViewUIView 的子类。
    • 保留视图最终状态的修改是什么?这是更大的圆圈。将animation.repeatCount 设置为1,将animation.autoreverses 设置为NO。将使圆圈动画变大,然后在没有动画的情况下立即变小。我希望圆圈保持大而不回到初始状态。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    相关资源
    最近更新 更多