我正在使用标准代码的-drawRect:
方法画一个圆圈。但是,我想稍微脉冲(变大和变小)并用动画改变颜色填充的强度。例如,如果圆圈充满红色,我想给圆圈打脉冲,并随着脉冲动作及时使红色稍微变亮和变暗。对Core Animation没有太多经验我对如何做到这一点有点迷茫,所以任何帮助将不胜感激。UIView
CGContextFillEllipseInRect()
问问题
14150 次
1 回答
71
如果你不画圆圈,这会简单得多drawRect:
。相反,将您的视图设置为使用 a 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;
}
于 2012-05-30T03:06:24.247 回答