界面如lol盒子摇一摇相同
首先实现手机晃动检测功能,导入<CoreMotion/CoreMotion.h>框架
@interface CJShakeViewController ()
{
NSTimer *timer;
CMMotionManager *shake;
}
定义一个CMMotionManager变量,这里使用的是pull方法,还有一种是push方法,详情请百度一下
//摇动检测
-(void)shakeAndShake
{
shake = [[CMMotionManager alloc]init];
if (!shake.accelerometerAvailable) {
NSLog(@"摇动不可用");
}
shake.accelerometerUpdateInterval = 0.1;
[shake startAccelerometerUpdates];
timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(updateAcc) userInfo:nil repeats:YES];
}
//监听摇动函数
-(void)updateAcc
{
[shake stopAccelerometerUpdates];
CMAccelerometerData *accData =shake.accelerometerData;
double x = accData.acceleration.x;
double y = accData.acceleration.y;
if (fabs(x)>1.0||fabs(y)>0.8) {
[self whatShouldIDowhileShaking];
}
[shake startAccelerometerUpdates];
}
在start之后别忘记添加对应的stopAccelerometerUpdate
然后实现图片抖动功能和手机震动功能
手机震动需要导入<AudioToolbox/AudioToolbox.h>框架
图片抖动需要导入<QuartzCore/QuartzCore.h>框架
//监听到抖动后需要做什么
-(void)whatShouldIDowhileShaking
{
[self changeAngle];
//手机震动一次
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
//图片抖动
-(void)changeAngle
{
CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"transform"];
//抖动启示位置
basic.fromValue = [NSNumber numberWithFloat:M_PI/16];
//抖动结束位置
basic.toValue = [NSNumber numberWithFloat:-M_PI/16];
basic.duration = 0.15;
basic.repeatCount = 3;
//将定义好的动画加入到需要抖动的图像上,并设置Key值
[_imageview.layer addAnimation:basic forKey:@"animateLayer"];
}
这样已经实现检测手机摇动,并且抖动图像,震动一次手机