开发者

Xcode iPhone accelerometer image

I'm French so excuse me for my English. So I use an accelerometer, but in my code the accelerometer works for a view and not for an image. What I want to do is to use this accelerometer for an image instead of a view. How can I do this? Here is the code:

#define CONST_fps 100.
#define CONST_map_shift 0.01
#define kFilteringFactor 0.1
UIAccelerationValue rollingX, rollingY, rollingZ;

@implementation MapViewRotationViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // accelerometer settings
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / CONST_fps)];
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));

    rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFac开发者_运维知识库tor));

    rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));

    float accelX = acceleration.x - rollingX;
    float accelY = acceleration.y - rollingY;
    float accelZ = acceleration.z - rollingZ;

    static CGFloat ZZ = 0.;
    CGFloat z = (atan2(rollingX, rollingY) + M_PI);

    if (fabsf(ZZ - z) > CONST_map_shift)
    {
        viewToRotate.layer.transform = CATransform3DMakeRotation(ZZ=z, 0., 0., 1.);
    }
}

@end


You don't need to have a view as callback instead you can choose any class to conform to protocol UIAccelerometerDelegate. Just declare your class in the header file as

@interface MyClass : NSObject <UIAccelerometerDelegate> {
  // my members
}

In MyClass.m you have to implement method

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
  // do what you like
}

But if you are not forced to support iOS version 3.x, you should consider using CoreMotion API. See Event Handling Guide for iOS / Motion Events for more information and samples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜