Question

Is there a framework or example code out there that shows how to use UIAccelerometer to control an onscreen level, similar to the bubble level apps?

I realize I need to use it like:

UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 1.0f/50.0f;

- (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler
{
    // get angle in radians
    float angle = atan2(aceler.x, aceler.y);
    // convert to degrees
    float angleInDegrees = (angle * 180/M_PI);

    NSLog(@"%.0f degrees",angleInDegrees);

    if (angleInDegrees > 90) {
        self.levelIndicator.center = CGPointMake(self.cachedLevel.x+angleInDegrees-90, self.cachedLevel.y);
    } else {
        self.levelIndicator.center = CGPointMake(self.cachedLevel.x-angleInDegrees+90, self.cachedLevel.y);
    }

}

How could I use the angleInDegrees to move a simple UIView left or right from center based on what the angle is? My attempt above wasn't very successful.

Était-ce utile?

La solution

Apple used to have some Sample code for exactly what you're after and it looks like someone has thought to save it even though Apple seems to no longer offer it on their dev site. ;)

Enjoy!

https://github.com/acekiller/iOS-Samples/tree/master/BubbleLevel

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top