径向渐变的动画中心

时间:2017-05-16 04:57:48

标签: ios core-graphics core-animation

如何为自定义CA图层中绘制的径向渐变的中心设置动画:

- (instancetype)init
{
self = [super init];
if (self) {
    [self setNeedsDisplay];
}
return self;
}

 - (void)drawInContext:(CGContextRef)ctx
{

size_t gradLocationsNum = 2;
CGFloat gradLocations[2] = {0.0f, 1.0f};
CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.5f};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
CGColorSpaceRelease(colorSpace);

CGPoint gradCenter= CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;

CGContextDrawRadialGradient (ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);


CGGradientRelease(gradient);
}

(来自https://stackoverflow.com/a/26924839/668518

有没有办法移动以这种方式绘制的径向渐变的中心?

1 个答案:

答案 0 :(得分:0)

您可以生成计时器或显示链接以在每个帧上触发刷新方法。

当您开始设置动画时,应将当前点保存到某个属性(self.animationStartPoint)并将目标点保存到某个属性(self.animationEndPoint)。然后将想要动画的2个日期保存为self.animationStartDate = [NSDate date]self.animationDate = [self.animationStartDate byAddingTimeInterval:animationDuration]。现在,当计时器或显示链接触发时,您只需要拨打[self setNeedsDisplay]

在绘制方法中,您现在需要插入两个点。首先,我们需要检查动画时间在哪里:

CGFloat scale = [[NSDate date] timeIntervalSince:self.animationStartDate] / [self.animationEndDate timeIntervalSince:self.animationStartDate];

虽然缩放比例应该在0和1之间。如果它小于动画仍在等待(如果你使用"延迟后#34;程序)。如果它大于动画结束:

if(scale < 0.0) return;
else if(scale > 1.0) {
   scale = 1.0;
   // TODO: report animation completed, invalidate timer or display link
}

然后使用比例找到当前点:

CGPoint gradCenter = CGPointMake(self.animationStartPoint.x + (self.animationEndPoint.x - self.animationStartPoint.x)*scale, self.animationStartPoint.y + (self.animationEndPoint.y - self.animationStartPoint.y)*scale);