有没有办法动画CGContextDrawRadialGradient iOS的颜色

时间:2014-03-28 12:24:48

标签: ios animation uiview uianimation

我使用CGContextDrawRadialGradient函数来制作渐变背景。

我重写drawRect:,如下所示:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // Create gradient
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = {0.0, 0.8};

    //  Neutral colors
    UIColor *centerColor    =   self.centerColor;
    UIColor *edgeColor      =   self.edgeColor;

    NSArray *colors = [NSArray arrayWithObjects:(__bridge id)centerColor.CGColor, (__bridge id)edgeColor.CGColor, nil];

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);

    // Scaling transformation and keeping track of the inverse
    CGAffineTransform scaleT = CGAffineTransformMakeScale(2, 1.0);
    CGAffineTransform invScaleT = CGAffineTransformInvert(scaleT);

    // Extract the Sx and Sy elements from the inverse matrix
    // (See the Quartz documentation for the math behind the matrices)
    CGPoint invS = CGPointMake(invScaleT.a, invScaleT.d);

    // Transform center and radius of gradient with the inverse
    //CGPoint center = CGPointMake((self.bounds.size.width / 2) * invS.x, (self.bounds.size.height / 2) * invS.y);
    CGPoint center = CGPointMake(-20, (self.bounds.size.height / 2) * invS.y);

    //CGFloat radius = (self.bounds.size.width / 2) * invS.x;

    CGFloat   radius = self.bounds.size.width;  // MEEEEE
    // Draw the gradient with the scale transform on the context
    CGContextScaleCTM(ctx, scaleT.a, scaleT.d);

    CGContextDrawRadialGradient(ctx, gradient, center, 0, center, radius, kCGGradientDrawsBeforeStartLocation);

    // Reset the context
    CGContextScaleCTM(ctx, invS.x, invS.y);

    // Continue to draw whatever else ...

    // Clean up the memory used by Quartz
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

并允许通过以下方式不时更改背景颜色:

- (void) setGradientCenterColor:(UIColor *)centerColor andEdgeColor:(UIColor *)edgeColor {
    self.centerColor = centerColor;
    self.edgeColor   = edgeColor;

    [self setNeedsDisplay];
}

有没有办法动画颜色属性?或者我需要手动完成?

非常感谢您提前回答:)

1 个答案:

答案 0 :(得分:0)

制作全球iVars NSArray *centerColorArray NSArray *edgeColorArrayNSInteger index

然后,在viewDidLoad

index = 0;
centerColorArray = @[@"color1", @"color2"];
edgeColorArray = @[@"color1", @"color2"];

使用NSTimer进行动画行为

-(void)animate
{
  [self changeColor:index];
  [YOUR_INSTANCE setGradientCenterColor:centerColor andEdgeColor:edgeColor];

  index++;
}

-(void)changeColor:(int)index
{
  if(index == [centerColorArray count] - 1)
    index = 0;

  centerColor = centerColorArray[index];
  edgeColor = edgeColorArray[index];
}

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(animate) userInfo:nil repeats:YES];