使用CABasicAnimation和CAShapeLayer制作计时器iOS动画

时间:2013-09-16 09:54:18

标签: ios animation cabasicanimation cashapelayer

我在测验游戏中为计时器制作了动画。 我想在动画中显示UIImageView * cronometro中的背景,但我的动画显示整个UIImageView。

我想在动画中制作:

Chrono OK

但我有这个:

Chrono wrong

这是我的代码:

//Chrono animation

-(void) startCronometro{

    //Set timer
    contoAllaRovescia = TIME;

    [cronometro setImage:[UIImage imageNamed:@"cronoStart.png"]];

    maskLayer = [CAShapeLayer layer];

    CGFloat maskHeight = cronometro.frame.size.height;
    CGFloat maskWidth = cronometro.frame.size.width;

    CGPoint centerPoint;
    centerPoint = CGPointMake(cronometro.frame.size.width/2, (cronometro.frame.size.height/2) + 3);//+3 because the image is not centered in UIImageView

    //Make the radius of our arc large enough to reach into the corners of the image view.
    CGFloat radius = sqrtf(maskWidth * maskWidth + maskHeight * maskHeight)/2;

    //Don't fill the path, but stroke it in black.
    maskLayer.fillColor = [[UIColor clearColor] CGColor];
    maskLayer.strokeColor = [[UIColor blackColor] CGColor];

    maskLayer.lineWidth = 30;

    CGMutablePathRef arcPath = CGPathCreateMutable();

    //Move to the starting point of the arc so there is no initial line connecting to the arc
    CGPathMoveToPoint(arcPath, nil, centerPoint.x, centerPoint.y-radius/2);

    //Create an arc at 1/2 our circle radius, with a line thickess of the full circle radius
    CGPathAddArc(arcPath, nil, centerPoint.x, centerPoint.y, radius/2, 3*M_PI/2, -M_PI/2, NO);

    maskLayer.path = arcPath;//[aPath CGPath];//arcPath;

    //Start with an empty mask path (draw 0% of the arc)
    maskLayer.strokeEnd = 0.1;

    CFRelease(arcPath);

    //Install the mask layer into out image view's layer.
    cronometro.layer.mask = maskLayer;

    //Set our mask layer's frame to the parent layer's bounds.
    cronometro.layer.mask.frame = cronometro.layer.bounds;

    //Create an animation that increases the stroke length to 1, then reverses it back to zero.
    CABasicAnimation *swipe = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    swipe.duration = TIME;
    swipe.delegate = self;
    // [swipe setValue:@"string" forKey:@"key"];
    swipe.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    swipe.fillMode = kCAFillModeForwards;
    swipe.removedOnCompletion = NO;
    swipe.toValue = [NSNumber numberWithFloat: 1.0];

    [maskLayer addAnimation: swipe forKey: @"strokeEnd"];

    //Aggiorno l'etichetta del conto alla rovescia ogni 0.1 millisecondi
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(whileCronometro) userInfo:nil repeats:YES];

}

谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您需要使用KeyFrame动画。您需要将路径传递给关键帧动画。因此它将在该路径上旋转。链接:Key Frame Animation