ios - drawRect 圆和动画大小/颜色

标签 ios ios5 core-animation quartz-graphics

我正在使用标准 CGContextFillEllipseInRect() 代码在 UIView-drawRect: 方法中绘制一个圆。但是,我想稍微脉动(变大和变小)并使用动画更改颜色填充的强度。例如,如果圆圈充满红色,我想使圆圈产生脉动,并随着脉动 Action 及时使红色稍微变亮和变暗。没有太多使用 Core Animation 的经验,我对如何做到这一点有点迷茫,所以非常感谢任何帮助。

最佳答案

如果您不在drawRect: 中绘制圆,这会简单得多。相反,将您的 View 设置为使用 CAShapeLayer,如下所示:

@implementation PulseView

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

每当 View 改变大小时(包括它首次出现时),系统都会将 layoutSubviews 发送到您的 View 。我们覆盖 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;
}

关于ios - drawRect 圆和动画大小/颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10809280/

相关文章:

ios - 使用 VFL 在 iOS 中实现自动布局

ios - 将 UIButton 的属性赋予 SpriteKit 中的 SKSpriteNode

ios - 关闭当前 View Controller 时 UIView 框架发生变化

multithreading - NSSplitViewItem 折叠动画和窗口 setFrame 冲突

ios - 重启cocos2d中的当前场景

ios - 将全局变量的值从 .m 获取到另一个 .m

ios - Xcode/ios 5 中的特殊字符到 SBJson

cocoa - 核心动画回调

objective-c - 使用 CGPoint 和 CATransform3D 在一条线上找到一个新点?

ios - 导航栏中的按钮图像具有不同的外观。为什么?