iOS日常开发

iOS仿ofo小黄人动态效果

2017-07-11  本文已影响71人  风与鸾

故事

最新版的ofo小黄人的动态效果简直帅爆了O(∩_∩)O哈哈~为ofo公司的码农、产品、UI点个赞,做为一个一线码农当然关注这个功能是怎么实现的,随后研究了下贴上自己的Demo传送门

思路

核心代码

- (void)updateAccelerometer
{
    self.motionManager = [[CMMotionManager alloc] init];
    //加速计可用
    if (self.motionManager.isAccelerometerAvailable) {
        //设置更新时间
        self.motionManager.accelerometerUpdateInterval = 0.01;
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            CMAcceleration acceleration = accelerometerData.acceleration;
            //NSLog(@"x:%f+++y:%f+++z:%f",acceleration.x,acceleration.y,acceleration.z);
            if (!error) {
                CGFloat x = self.eyeImageView.center.x + acceleration.x * self.velocity;
                CGFloat y = self.eyeImageView.center.y + acceleration.y * self.velocity;
                if (x < self.eyeImageView.width / 2) {
                    x = self.eyeImageView.width / 2;
                }else if (x > self.width - self.eyeImageView.width / 2){
                    x = self.width - self.eyeImageView.width / 2;
                }
                
                if (y < self.eyeImageView.height / 2) {
                    y = self.eyeImageView.height / 2;
                }else if (y > self.height - self.eyeImageView.height / 2)
                {
                    y = self.height - self.eyeImageView.height / 2;
                }
                self.eyeImageView.center = CGPointMake(x, y);
            }
            
            CGFloat r = self.width /2 - self.eyeImageView.width /2;
            CGPoint center = CGPointMake(self.width /2, self.height/2);
            CGPoint currentPoint = self.eyeImageView.center;
            CGFloat x = 0;
            CGFloat y = 0;
            //斜边
            CGFloat c = sqrt(pow(center.x - currentPoint.x, 2) + pow(currentPoint.y - center.y, 2));
            if (c > r) {
                //邻边
                CGFloat b = fabs(r * (center.x - currentPoint.x) / c);
                //对边
                CGFloat a = fabs(r * (currentPoint.y - center.y) / c);
                if (currentPoint.x > center.x) {
                    x = center.x + b;
                }else {
                    x = center.x - b;
                }
                if (currentPoint.y > center.y) {
                    y = center.y + a;
                }else {
                    y = center.y - a;
                }
                self.eyeImageView.center = CGPointMake(x, y);
            }
        }];
    }
}

一开始在限制眼睛活动范围花了点时间,已知eye的center点和self.center可求出两点的距离再利用余弦和正弦分别求出邻边和对边的值,即可算出eye最适合范围。

上一篇下一篇

猜你喜欢

热点阅读