2013-10-29 24 views
0

有没有办法改变UIView的foregroundColor?更改UIView的foregroundColor

我创建了一个使用UIView(drawRect)的箭头,就像这个“>”,背景清晰,只有两条黑线。这很好。但之后我想将“>”的颜色从黑色更改为红色。使用CAKeyframeAnimation可以很好地使用动画,例如从黑色到红色的渐变。我可以做borderColor和backgroundColor,但这些属性不是我正在寻找的。

我使用这个动画块更改另一个UIView的borderColor。我想对foregroundColor做同样的事情,但它不适用于iOS。

CAKeyframeAnimation* colorAnim = [CAKeyframeAnimation animationWithKeyPath:@"borderColor"]; 
NSArray* colorValues = [NSArray arrayWithObjects:(id)[UIColor blackColor].CGColor,(id)[UIColor redColor].CGColor, nil]; 
colorAnim.values = colorValues; 
colorAnim.calculationMode = kCAAnimationPaced; 
colorAnim.duration = 5.0; 
colorAnim.repeatCount = 1; 
[self.myView.layer addAnimation:colorAnim forKey:@"borderColor"]; 

我感谢任何帮助,谢谢!

回答

0

UIView类没有foregroundColor属性,所以您必须自己实现它。在你的UIView子类接口,定义属性:

@property (nonatomic, strong) UIColor *foregroundColor; 

在你的子类实现,覆盖setForegroundColor: setter方法:

- (void)setForegroundColor:(UIColor *)newForegoundColor 
{ 
    _foregroundColor = newForegroundColor; 
    [self setNeedsDisplay]; // This is need so that drawRect: is called 
} 

在哪个初始化器你正在使用在子类中,设置foregroundColor属性默认:

self.foregroundColor = [UIColor blackColor]; 

在你drawRect:实现,使用foregroundColor属性以抚摸你正在画的雪佛龙:

CGContextSetStrokeColorWithColor(context, self.foregroundColor.CGColor); 
+0

嗨,首先,非常感谢你的答案。我做了你所建议的一切,新的属性工作得很好,但动画并没有改变子视图的颜色。我打电话是这样的: 'CAKeyframeAnimation * colorAnim2 = [CAKeyframeAnimation animationWithKeyPath:@ “foregroundColor”];'' = colorAnim2.values colorValues;'' = colorAnim2.calculationMode kCAAnimationPaced;'' = colorAnim2.duration 5.0 ;' 'colorAnim2.repeatCount = 1;' '[self.balloonTriangleBorder.layer addAnimation:colorAnim forKey:@“foregroundColor”];' – Fabio

+0

要让自定义属性具有动画效果,您必须在'CALayer '子类和[重写'needsDisplayForKey:'](http://stackoverflow.com/questions/14192816/create-a-custom-animatable-property)。 – neilco

+0

好的,我会试试。不管怎样,谢谢! – Fabio