Alessandro
Alessandro

Reputation: 4100

Rotating a UIImage fixing angle turn

I have a UIImage, and I want the user to be able to rotate it just like if it was the turning button of a safe. I don't want the image to turn at any angle in the range 0 < x < 360, but I want the wheel (the UIImage) to stop at one of the fixed points, which vary (normally form 0 to 20). If for example I have 3 options, the user will be able to turn the wheel and to place the pointer just on the three point (in this case at angles: 60, 120, 180). I use this code to rotate the image:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSSet *allTouches = [event allTouches];

    int len = [allTouches count]-1;

    UITouch *touch =[[allTouches allObjects] objectAtIndex:len];
    CGPoint location = [touch locationInView:[self.SplashItGroupPicker superview]];
    float theAngle = atan2( location.y-self.SplashItGroupPicker.center.y, location.x-self.SplashItGroupPicker.center.x );

    int totalRadians = -3.14;

    totalRadians += fabs(theAngle - totalRadians);
    totalRadians = fmod(totalRadians, 2*M_PI);

    [self rotateImage:totalRadians];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}

-(void) rotateImage:(float)angleRadians{
    self.SplashItGroupPicker.transform = CGAffineTransformMakeRotation(angleRadians);
    CATransform3D rotatedTransform = self.SplashItGroupPicker.layer.transform;
    self.SplashItGroupPicker.layer.transform = rotatedTransform;
} 

How can I obtain that result?

Upvotes: 0

Views: 432

Answers (1)

Brendon
Brendon

Reputation: 882

Find how many radians you need per step, e.g. if you want 4 positions, then each position will be 3.14 / 4 radians more than the last. Call this radIncrement.

After this line

totalRadians = fmod(totalRadians, 2*M_PI);

divide totalRadians by radIncrement, round the result to an integral value, then multiply it again by radIncrement. You can change your rounding behavior to tweak when it changes positions.

Upvotes: 1

Related Questions