Search code examples
iosswiftvirtual-reality

Panning an image/images in Swift using an iPad compass


I have four images; each is 350 pixels wide; I have the text North on the first, East on the second, South on the third and West on the fourth. I put them into a scrollView in a single image and I link said scrollView to the direction I am pointing my iPad. Now as I pan around I want the scroll to pan around the images, so if I am looking north and turn east I see north slide of the screen and east onto it.

Now I tried to do this using the compass, and it works reasonably well, but how to code crossing the boundary between 0 degrees and 360 degrees is a challenge. I tried using yaw so that I am looking at two 180 degree circles, but working out how to make that work has evaded me too. I google this and find quaternion and euler angles, but nothing that makes enough sense to me...

Need some direction/help.


Solution

  • You don't really need a scroll view for this, since you are controlling the scroll offset by device heading rather than by letting the user swipe the screen. So you could just use a plain old UIView as the parent of the image views. You would just update view.bounds.origin instead of scrollView.contentOffset to “scroll”. (Under the hood, the scroll view's contentOffset is the same as its bounds.origin.)

    Anyway, lay out your images like this:

    +-------+-------+-------+-------+-------+
    | North |  East | South |  West | North |
    +-------+-------+-------+-------+-------+
    

    Note that the North image is used twice.

    When you get a new heading, update the offset of the scroll view like this:

    let range = CGFloat(350 * 4)
    let offset = range * (CGFloat)direction / 360
    scrollView.contentOffset = CGPointMake(offset, 0)