Hello, I puzzle over the following: I need to have a horizon level on the phone so that it is displayed as a line or accurate, but when the phone is rotated (in any plane), this line goes either up or down. (We hold the phone in our hands, either portrait or landscape orientation)

To understand: Take a pencil horizontally at eye level and rotate your head in any direction, the line of the pencil (it’s the horizon) will either move up (if your head is downward), etc. Here you need something the same to do on the iPhone. A vivid example of this is the spirit level application in the standard set of iPhone (open the compass and swipe to the left do)

I know how to transform the line for example to be always horizontal, regardless of the rotation of the phone:

CMDeviceMotion *data; double rotation = atan2(data.gravity.x, data.gravity.y) + M_PI; self.myLineHoriz.transform = CGAffineTransformMakeRotation(rotation); 

But how to make the line tilt up or down from the tilt of the phone ??

It is necessary to calculate the center of coordinates of this line and change it depending on the slope. I've been puzzling for several days now, but there are no positive thoughts.

    1 answer 1

    This is a complex task in reality. I will describe all the problems:

    1. The tilt data of the device is obtained from the accelerometer. This means that with its own movement the device will affect its readings. You can work simultaneously with the accelerometer and gyroscope, that is, to “calibrate” the gyroscope with the average readings of the accelerometer and consider the inclination of the device along the gyroscope. I am almost sure that such algorithms have already been written.
    2. The camera is located in the corner of the device, and not in its middle. That is, the rotation of the device is not around the camera, but around the center, as the user would have done, will create a precession of the objects to be corrected. But the horizon line in this case is an infinitely distant object, so there should be no problems for it.
    3. The camera has its own viewing angle - it must be taken into account in order to determine whether the rotation of the device by 1 degree will shift the horizon line horizontally.
    4. Cameras of different devices may have a different viewing angle - this will need to be established empirically, or better read in the specification
    5. Accelerometer readings used in view of the current orientation of the interface.
    6. Previously, AR-views, which showed the direction to an object in camera mode, were popular, the best of them, I think, should have had a solution to all the problems described. Type such https://github.com/zac/iphonearkit https://github.com/calonso/ios-arkit