【问题标题】:Animate Center of Radial Gradient径向渐变动画中心
【发布时间】:2017-05-16 04:57:48
【问题描述】:

如何为自定义 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

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

【问题讨论】:

    标签: ios core-graphics core-animation


    【解决方案1】:

    您可以生成一个计时器,或者更确切地说是一个显示链接来触发每一帧的刷新方法。

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

    在 draw 方法中,您现在需要对两个点进行插值。首先我们需要检查动画时间在哪里:

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

    在设置动画时,比例应该在 0 和 1 之间。如果小于,则动画仍在等待(如果您使用“延迟后”程序)。如果大于动画结束:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多