如何让UIImageView始终面向加速度计?

时间:2011-08-26 05:09:32

标签: uiimageview rotation accelerometer

我想在用户旋转设备(任意角度,而不仅仅是风景/肖像)时,UIImageView始终朝上。我该怎么做?

提前致谢

1 个答案:

答案 0 :(得分:0)

@interface FirstViewController : UIViewController <UIAccelerometerDelegate> {
    IBOutlet UIImageView *imageView;
    CGPoint delta;
    CGPoint translation;
    float ballRadius;  
}

//implementation

- (void)viewDidLoad
{    
    [super viewDidLoad];

    // for the line in the middle of the camera
    UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
    accel.delegate = self;
    accel.updateInterval = 1.0f/60.0f;        
}

- (void)accelerometer:(UIAccelerometer *)acel
        didAccelerate:(UIAcceleration *)acceleration {

    // Get the current device angle
    float xx = -[acceleration x]; 
    float yy = [acceleration y]; 
    float angle = atan2(yy, xx); 

    // Add 1.5 to the angle to keep the image constantly horizontal to the viewer.
    [imageView setTransform:CGAffineTransformMakeRotation(angle+1.5)]; 

}