【问题标题】:Change foregroundColor of a UIView更改 UIView 的前景颜色
【发布时间】:2013-10-29 10:46:17
【问题描述】:

有没有办法改变 UIView 的前景颜色?

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

我正在使用这个动画块更改另一个 UIView 的边框颜色。我想对 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"];

感谢您的帮助,谢谢!

【问题讨论】:

    标签: ios iphone objective-c


    【解决方案1】:

    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);
    

    【讨论】:

    • 您好,首先非常感谢您的回答。我做了你建议的一切,新属性运行良好,但动画没有改变子视图的颜色。我这样打电话: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"];
    • 要使自定义属性可动画化,您必须在 CALayer 子类和 override needsDisplayForKey: 中进行绘图。
    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 2014-09-25
    • 1970-01-01
    • 2017-05-30
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    相关资源
    最近更新 更多