Curnelious
Curnelious

Reputation: 1

Rotating a wheel?

I have read here a few examples about that, but couldn't make it work. I have some UIView called Wheel , in which i want to rotate while touch and drag. It should work like a real wheel, so if i touch at some point it will NOT rotate to that point, only when i drag my finger, i will get rotation .

I tried this,but i get a full rotation for every little move i do. I would like to ADD the angel to the view, not ROTATE to the new angel ..

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

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self];

    CGPoint center=wheel.center;

    float xLeg = fabs(center.x - touchPoint.x);
    float yLeg = fabs(center.y-touchPoint.y);
    float angle = atan(xLeg / yLeg);


    NSLog(@"%f",angle);
      wheel.transform = CGAffineTransformMakeRotation( angleInDegree );

}

Upvotes: 0

Views: 138

Answers (1)

Dennis
Dennis

Reputation: 2165

This should do the trick. Notice how I store the first touch point in touchesBegan:withEvent:. This allows me to subtract the first touch point from every touch point I get while dragging, and thus gives me the real angle I need to rotate.

EDIT

I've done some adjustments, so that it is now smooth and regular even after several touches.

Demo

enter image description here

WheelViewController.m

@interface WheelViewController () {
    CGPoint startPoint;
    CGFloat startAngle;
    CGFloat endAngle;
}

@end

@implementation WheelViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    startPoint = [touch locationInView:self.view];
    startAngle = [self angleForTouchPoint:startPoint] - endAngle;

    NSLog(@"\r\nStart angle: %f", startAngle);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    CGFloat touchAngle = [self angleForTouchPoint:touchPoint];

    NSLog(@"Touch angle: %f", touchAngle);

    self.wheel.transform = CGAffineTransformMakeRotation(fmodf(touchAngle - startAngle, 2 * M_PI));
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    endAngle = [self angleForTouchPoint:touchPoint] - startAngle;

    NSLog(@"End angle: %f", endAngle);
}

- (CGFloat)angleForTouchPoint:(CGPoint)touchPoint {
    CGPoint center = self.wheel.center;

    float xLeg = touchPoint.x - center.x;
    float yLeg = touchPoint.y - center.y;

    float angle = fmodf(atan(yLeg/xLeg), (2 * M_PI));

    if (xLeg < 0) {
        angle += M_PI;
    }

    return angle;
}

Upvotes: 1

Related Questions