自定义一个Animation类继承UIWindow
由于获知手机摇动是结合硬件的底层东西,所以要直接在appdelegate里面自定义一个window,这也是Animation这个类的用途。
下面开始讲述代码:
在AppDelegate.h文件里面导入Animation头文件声明一个aWindow
然后在AppDelegate.m文件中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中实现你写的界面例如:
self.aWindow=[[[Animation alloc]initWithFrame:[[UIScreen mainScreen]bounds] ]autorelease];
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
} else {
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
}
UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:self.viewController];
nav.navigationBarHidden=YES;
[self.aWindow addSubview:nav.view];
[self.aWindow makeKeyAndVisible];
然后介绍Animation类的内容:
在.h文件中声明一个协议方法-(void)AnimateOnePhone;
在.m文件中引用系统的两个接收震动手机的方法
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"--------开始摇一摇-------");
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion==UIEventSubtypeMotionShake) {
[[NSNotificationCenter defaultCenter]postNotificationName:@"StartAnimate" object:self];
}
}
最后在你所需要接受摇动手机信息的界面作如下操作:
导入头文件
#import<QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
声明一个SystemSoundID soundID;
在- (void)viewDidLoad中写如下代码接受通知
NSString *path = [[NSBundle mainBundle] pathForResource:@"glass" ofType:@"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addAnimations) name:@"StartAnimate" object:nil];
自定义一个调用方法
#pragma mark - 摇一摇动画效果
- (void)addAnimations
{
AudioServicesPlaySystemSound (soundID);
//让imgup上下移动
CABasicAnimation *translation2=[CABasicAnimation animationWithKeyPath:@"position"];
translation2.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
//以图片的中心算起的坐标
translation2.fromValue=[NSValue valueWithCGPoint:CGPointMake(160, 115)];
translation2.toValue=[NSValue valueWithCGPoint:CGPointMake(160, 40)];
translation2.duration=0.5;
translation2.repeatCount=1;
translation2.autoreverses=YES;
//让imagdown上下移动
CABasicAnimation *translation = [CABasicAnimation animationWithKeyPath:@"position"];
translation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//以图片的中心算起的坐标
translation.fromValue = [NSValue valueWithCGPoint:CGPointMake(160, 345)];
translation.toValue = [NSValue valueWithCGPoint:CGPointMake(160, 420)];
translation.duration = 0.5;
translation.repeatCount = 1;
translation.autoreverses = YES;
[bottomImg.layer addAnimation:translation forKey:@"translation"];
[upImg.layer addAnimation:translation2 forKey:@"translation2"];
}