您的位置:首页 > 移动开发 > 微信开发

IOS 仿微信摇一摇

2015-09-07 17:35 561 查看
本来觉得摇一摇很难的,今天百度一下才知道这么简单,还是IOS封装的好,很多代码都简化了。
只需要自己把摇一摇的动画做好就可以了。和声音的功能。

说下思路吧:

 1 摇一摇动画就是监听手机晃动,手机晃动后触发 motionBegan 方法

 2 调用声音,开始动画。

 A 震动的回调函数。

#pragma mark -摇一摇

- (BOOL)canBecomeFirstResponder
{
    // default is NO
    return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"shake");  
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"stop");    
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"cancel");
}

 B 动画方面我是用的简单的 CABasicAnimation
直接封装成方法即可。 里面动画开始和结束的坐标需要自己修改一下。
我再5S上测试没问题。

#pragma mark - 摇一摇动画效果
- (void)addAnimations
{
    CGFloat imgW=self.view.bounds.size.width;
    CGFloat imgH=self.view.bounds.size.height;
    
    //让down上下移动
    CABasicAnimation *translation = [CABasicAnimationanimationWithKeyPath:@"position"];
    translation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    translation.fromValue = [NSValuevalueWithCGPoint:CGPointMake(imgW/2,400)];
    translation.toValue = [NSValuevalueWithCGPoint:CGPointMake(imgW/2,550)];
    translation.duration =
0.4;
    translation.repeatCount =
1;
    translation.autoreverses =
YES;
    
    //让up上下移动
    CABasicAnimation *translation1 = [CABasicAnimationanimationWithKeyPath:@"position"];
    translation1.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    translation1.fromValue = [NSValuevalueWithCGPoint:CGPointMake(imgW/2,115)];
    translation1.toValue = [NSValuevalueWithCGPoint:CGPointMake(imgW/2,40)];
    translation1.duration =
0.4;
    translation1.repeatCount =
1;
    translation1.autoreverses =
YES;
    
    [self.down.layeraddAnimation:translationforKey:@"translation"];
    [self.up.layeraddAnimation:translation1forKey:@"translation1"];

}

 C 调用声音:

在 viewDidLoad里面

NSString *path = [[NSBundlemainBundle]pathForResource:@"shake"ofType:@"wav"];
    if (path) {
        //注册声音到系统
        AudioServicesCreateSystemSoundID((__bridgeCFURLRef)[NSURLfileURLWithPath:path],&shake_sound_male_id);
    }

然后自定义方法 这样用到的时候调用即可。

-(void) playSound

{
    //播放注册的声音,(此句代码,可以在本类中的任意位置调用,不限于本方法中)
    AudioServicesPlaySystemSound(shake_sound_male_id);
    //让手机震动
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

最后在模拟器的效果图片
我是在真机测试的。这里只是截图。



需要注意的是,模拟器不恩运行,只能在真机运行,添加证书修改ID即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: