Подтвердить что ты не робот

Перемещение изображения с помощью эффекта параллакса ios 7

Я только что увидел новое приложение для Facebook, в котором изображения перемещаются на основе эффекта параллакса. Таким образом, он увеличит изображение до полноэкранного режима, и когда вы наклоняете экран, он прокручивает изображение в сторону, на которую вы наклонены. Я смог добавить эффект параллакса, как у яблока, но не так, как в facebook. У кого-нибудь есть идеи, как они это сделали. Вот базовый код, который я использовал для параллакса:

UIInterpolatingMotionEffect *interpolationHorizontal = [[UIInterpolatingMotionEffect alloc]initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
interpolationHorizontal.minimumRelativeValue = @-10.0;
interpolationHorizontal.maximumRelativeValue = @10.0;

UIInterpolatingMotionEffect *interpolationVertical = [[UIInterpolatingMotionEffect alloc]initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
interpolationVertical.minimumRelativeValue = @-10.0;
interpolationVertical.maximumRelativeValue = @10.0;

[self.backgroundView addMotionEffect:interpolationHorizontal];
[self.backgroundView addMotionEffect:interpolationVertical];
4b9b3361

Ответ 1

Update: Просто нашел очень приятную стороннюю библиотеку для достижения этой цели, она называется CRMotionView, она работает очень гладко, и вы можете многое изменить.

вот ссылка github: https://github.com/chroman/CRMotionView

=============================================== ===================================

Я думал о том же параллаксе, когда впервые увидел приложение для работы с Facebook. но после игры с моим кодом немного, я не думаю, что параллакс - это то, что мы ищем. Я мог ошибаться, но я пошел делать все это из базы, менеджера гироскопов. Вот мой пример кода:

     //import the motion manager frame work first
     #import <CoreMotion/CoreMotion.h>

     //then need to add a motionManager
     @property (strong, nonatomic) CMMotionManager *motionManager;

    //you can paste all those codes in view did load
    //i added a scroll view on the view controller nib file
    self.mainScrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    //we don't want it to bounce at each end of the image
    self.mainScrollView.bounces = NO;

    //and we don't want to allow user scrolling in this case
    self.mainScrollView.userInteractionEnabled = NO;

    //set up the image view
    UIImage *image= [UIImage imageNamed:@"YOUR_IMAGE_NAME"];
    UIImageView *movingImageView = [[UIImageView alloc]initWithImage:image];
    [self.mainScrollView addSubview:movingImageView];

    //set up the content size based on the image size
    //in facebook paper case, vertical rotation doesn't do anything
    //so we dont have to set up the content size height
    self.mainScrollView.contentSize = CGSizeMake(movingImageView.frame.size.width, self.mainScrollView.frame.size.height);

    //center the image at intial
    self.mainScrollView.contentOffset = CGPointMake((self.mainScrollView.contentSize.width - self.view.frame.size.width) / 2, 0);

    //inital the motionManager and detec the Gyroscrope for every 1/60 second
    //the interval may not need to be that fast
    self.motionManager = [[CMMotionManager alloc] init];
    self.motionManager.gyroUpdateInterval = 1/60;

    //this is how fast the image should move when rotate the device, the larger the number, the less the roation required.
    CGFloat motionMovingRate = 4;

    //get the max and min offset x value
    int maxXOffset = self.mainScrollView.contentSize.width - self.mainScrollView.frame.size.width;
    int minXOffset = 0;

    [self.motionManager startGyroUpdatesToQueue:[NSOperationQueue currentQueue]
                                withHandler:^(CMGyroData *gyroData, NSError *error) {
         //since our hands are not prefectly steady
         //so it will always have small rotation rate between 0.01 - 0.05
         //i am ignoring if the rotation rate is less then 0.1
         //if you want this to be more sensitive, lower the value here
         if (fabs(gyroData.rotationRate.y) >= 0.1) {
            CGFloat targetX = self.mainScrollView.contentOffset.x - gyroData.rotationRate.y * motionMovingRate;
             //check if the target x is less than min or larger than max
             //if do, use min or max
             if(targetX > maxXOffset)
                   targetX = maxXOffset;
             else if (targetX < minXOffset)
                   targetX = minXOffset;

             //set up the content off
             self.mainScrollView.contentOffset = CGPointMake(targetX, 0);
          }
   }];

Я тестировал это на своем устройстве, работал очень похоже на новое приложение для facebook.

Однако, это всего лишь пример кода, который я написал за полчаса, может быть не на 100% точным, но надеюсь, что это даст вам некоторые идеи.