I need some help.How to rotate UIButton or UIImageView that follows finger (Touch and hold, UILongPressGestureRecognizer)? Thx 4 help
UPD: Don't understand what i'm doing wrong?
- (void)viewDidLoad {
UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[self.view addGestureRecognizer:tapgr];
[tapgr release];
[super viewDidLoad];
}
-(void)tap:(UITapGestureRecognizer *)gesture {
CGPoint touch = [gesture locationInView:self.view];
CGPoint center = myImage.center;
float dx,dy,wtf;
dx = touch.x-center.x;
dy = touch.y-center.y;
wtf = atan2f(dy, dx);
[self rotateImage:self.myImage withAngle:wtf];
}
- (void)rotateImage:(UIImageView *)image withAngle:(float)newAngle
{ image.transform = CGAffineTransformMakeRotation(newAngle);
}
Glad I remember triginometry
-(void)degreesToRotateObjectWithPosition:(CGPoint)objPos andTouchPoint:(CGPoint)touchPoint{
float dX = touchPoint.x-objPos.x; // distance along X
float dY = touchPoint.y-objPos.y; // distance along Y
float radians = atan2(dY, dX); // tan = opp / adj
//Now we have to convert radians to degrees:
float degrees = radians*M_PI/360;
return degrees;
}
Once you have your nice method, just do this in the touch event method. (I forgot what it's called...)
CGAffineTransform current = view.transform;
[view setTransform:CGAffineTransformRotate(current,
[self degreesTorotateObjectWithPosition:view.frame.origin
andTouchPoint:[touch locationInView:]]
//
This is pretty much all the code that you'll need.The math is right, but I'm not sure about the setTransform stuff. I'm at school writing this in a browser. You should be able to figure it out from here.
Good luck,
Aurum Aquila
- (void) LongPress:(UILongPressGestureRecognizer *)gesture {
CGPoint p = [gesture locationInView:self.view];
CGPoint zero;
zero.x = self.view.bounds.size.width / 2.0;
zero.y = self.view.bounds.size.height / 2.0;
CGPoint newPoint;
newPoint.x = p.x - zero.x;
newPoint.y = zero.y - p.y;
angle = atan2(newPoint.x, newPoint.y);
UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState|UIViewAnimationOptionAllowUserInteraction;
[UIView animateWithDuration:0.2 delay:0.0 options:options
animations:^{myButton.transform = CGAffineTransformRotate(CGAffineTransformIdentity, angle);}
completion:^(BOOL finished) {
[UIView animateWithDuration:1.0 delay:0.5 options:options animations:^{
myButton.transform = CGAffineTransformRotate(CGAffineTransformIdentity, [self detectQuarter:angle]);
} completion:nil];
}];
}
#define M_PI_3_4 3*M_PI_4
-(CGFloat)detectQuarter:(CGFloat)anAngle {
if ((anAngle >= -M_PI_4)&&(anAngle <= M_PI_4)) return 0;
if ((anAngle > M_PI_4) && (anAngle <= 3*M_PI_4)) return M_PI_2;
if ((anAngle >= -M_PI_3_4) && (anAngle < -M_PI_4)) return -M_PI_2;
else return M_PI;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.