7

ビューをシェイクするために以下のコードを使用し、正常に動作します。ウィンドウをシェイクしたいので、コードで太字にした 2 行を code2 で変更しますが、機能しません。

//-------- code 1
CGFloat DegreesToRadians(CGFloat degrees)
{
    return degrees * M_PI / 180;
}

NSNumber* DegreesToNumber(CGFloat degrees)
{
    return [NSNumber numberWithFloat:
            DegreesToRadians(degrees)];
}
---------------
[self.view setWantsLayer:YES];

CAKeyframeAnimation * animation= [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
[animation setDuration:0.04];
[animation setRepeatCount:10];

srand([[NSDate date] timeIntervalSince1970]);
float rand = (float)random();
[animation setBeginTime:CACurrentMediaTime() + rand * .0000000001];

NSMutableArray *values = [NSMutableArray array];
[values addObject:DegreesToNumber(-1)];
[values addObject:DegreesToNumber(1)];
[values addObject:DegreesToNumber(-1)];    
[animation setValues:values];        
[self.view.layer addAnimation:animation forKey:@"rotate"];


//-------- code 2 
[self.window.animator addAnimation:animation forKey:@"rotate"];
[self.window.animator setWantsLayer:YES];
4

4 に答える 4

11

を追加する必要がありQuartzCore Frameworkます。

次に、次を使用します。

#import <Quartz/Quartz.h>


//below action calls the method `shakeWindow`

- (IBAction)shake:(id)sender {
    [self shakeWindow];
}

-(void)shakeWindow{

    static int numberOfShakes = 3;
    static float durationOfShake = 0.5f;
    static float vigourOfShake = 0.05f;

    CGRect frame=[self.window frame];
    CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animation];

    CGMutablePathRef shakePath = CGPathCreateMutable();
    CGPathMoveToPoint(shakePath, NULL, NSMinX(frame), NSMinY(frame));
    for (NSInteger index = 0; index < numberOfShakes; index++){
        CGPathAddLineToPoint(shakePath, NULL, NSMinX(frame) - frame.size.width * vigourOfShake, NSMinY(frame));
        CGPathAddLineToPoint(shakePath, NULL, NSMinX(frame) + frame.size.width * vigourOfShake, NSMinY(frame));
    }
    CGPathCloseSubpath(shakePath);
    shakeAnimation.path = shakePath;
    shakeAnimation.duration = durationOfShake;

    [self.window setAnimations:[NSDictionary dictionaryWithObject: shakeAnimation forKey:@"frameOrigin"]];
    [[self.window animator] setFrameOrigin:[self.window frame].origin];

}
于 2014-05-06T10:05:30.143 に答える