How To Rotate an UIImageView based on a point in Touches Moved Method? - iphone

Dear All,
I want to rotate a UIImageView relative to a point in touchesMoved method.
I tried 2 -3 methods but I am not getting the exact result what I expected to be.
First method I used
CGAffineTransform transforms = CGAffineTransformMakeRotation(M_PI/2);
imgView.transform = transforms;
This is written in touchesMoved. So I expect a rotation for the image view in each touchesMoved.
But the rotation is occuring only once .
Second method I used was
CGAffineTransform transforms = CGAffineTransformRotate(imgView.transform, M_PI/2);
imgView.transform = transforms;
Now the result what I get is the image in Image view is continusely rotating in each move. But imageview is not rotating. What i need is to rotate the imageview not the image.
Any help will be greatly appreciated.
Thanks & Best Regards,
Rupesh R Menon

If I understood correctly you want to achieve single finger rotation on the image. If it is so you can use following functions from one of my live working project. You can use this for single image as well as multiple images. You need to modify at some extend for multiple images. Best way is extend UIImageView class and create your own class.
From touches moved call this function
[self transformImagewithTouches:touch];
Declare 1 property and synthesize as follows. (Also please declare other variables if required in below code.
#property (nonatomic) CGFloat fltRotatedAngle;
-(void)transformImagewithTouches:(UITouch *)touchLocation
{
//NSLog(#"Before %f",self.fltRotatedAngle);
CGPoint touchLocationpoint = [touchLocation locationInView:[self superview]];
CGPoint PrevioustouchLocationpoint = [touchLocation previousLocationInView:[self superview]];
CGPoint origin;
origin.x=self.center.x;
origin.y=self.center.y;
CGPoint previousDifference = [self vectorFromPoint:origin toPoint:PrevioustouchLocationpoint];
CGAffineTransform newTransform =CGAffineTransformScale(self.transform, 1, 1);
CGFloat previousRotation = atan2(previousDifference.y, previousDifference.x);
CGPoint currentDifference = [self vectorFromPoint:origin toPoint:touchLocationpoint];
CGFloat currentRotation = atan2(currentDifference.y, currentDifference.x);
CGFloat newAngle = currentRotation- previousRotation;
//Calculate Angle to Store
fltTmpAngle = fltTmpAngle+newAngle;
self.fltRotatedAngle = (fltTmpAngle*180)/M_PI;
newTransform = CGAffineTransformRotate(newTransform, newAngle);
[self animateImageView:self toPosition:newTransform];
}
-(void)animateImageView:(UIImageView *)theView toPosition:(CGAffineTransform) newTransform
{
[UIView setAnimationsEnabled:YES];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.0750];
self.transform = newTransform;
[UIView commitAnimations];
}
-(CGPoint)vectorFromPoint:(CGPoint)firstPoint toPoint:(CGPoint)secondPoint
{
CGFloat x = secondPoint.x - firstPoint.x;
CGFloat y = secondPoint.y - firstPoint.y;
CGPoint result = CGPointMake(x, y);
return result;
}
Hope it helps. If you stuck up please let me know I ll definitely help you.

Thanks for the interest shown by you in helping me.
When I used the following code I was able to rotate the image view in my desired angle.
imgView.layer.transform = CATransform3DMakeRotation(pCalculator.tangentToCornerAngle, 0, 0, 1);
where imgView is an UIImageView.
pCalculator.tangentToCornerAngle is the desired angle in which rotation has to be made.
Function is CATransform3DMakeRotation(CGFloat angle, CGFloat x, <CGFloat y, CGFloat z);
Thankyou All,
Rupesh R Menon

It's because you have rotated it by M_PI/2 and when you rotate it again it rotates it from the initial position. Use this one
CGAffineTransform transforms = CGAffineTransformConcat(imgView.transform,CGAffineTransformMakeRotation(M_PI/2));
imgView.transform = transforms;

Related

How to change for 3D rotation on UIPanGesture?

I have done animation opening a page on tapping on it but now I have to change it for Pan Gesture. How should I start?
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
CALayer *layer = ges.view.layer;
CATransform3D initialTransform = ges.view.layer.transform;
initialTransform.m34 = 1.0 / -1100;
layer.transform = initialTransform;
layer.anchorPoint = CGPointMake(-0.0, 0.5);
[UIView beginAnimations:#"Scale" context:nil];
[UIView setAnimationDuration:2];
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];
CATransform3D rotationAndPerspectiveTransform = ges.view.layer.transform;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, -M_PI , 0 , -ges.view.bounds.size.height/2, 0);
ges.view.transform = CGAffineTransformRotate(ges.view.transform, 0);
layer.transform = rotationAndPerspectiveTransform;
[UIView setAnimationDelegate:self];
[UIView commitAnimations];
UIPanGestureRecognizer myPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(imagePanned:)];
[_panGesture setMaximumNumberOfTouches:1];
[yourView addGestureRecognizer:myPanGesture];
1) if you want page to turn along with the pan action as user moves the view then you have to do this way.
- (void)imagePanned:(UIPanGestureRecognizer *)iRecognizer {
CGPoint translation = [recognizer translationInView:self.view];
//Calculate transformation based on the translation value of pan gesture, this will be a tricky part
[UIView animateWithDuration:0.5 delay: 0 options: 0 animations:
^(void) {
//Apply transformation
}
completion: nil];
}
Hope this will help you.
Edit : Extended Answer
*This goes with the first idea*
You just want to rotate the view right ?
then use CATransform3D, here you will need to calculate the iAngle that we are applying to view.
iAngle = //Calculate based on translation
where translation is
CGPoint translation = [recognizer translationInView:self.view];
Then apply transformation to view
CATransform3D myTransform = CATransform3DIdentity;
myTransform.m34 = 1.0 / -500;
myTransform = CATransform3DRotate(myTransform, DEGREES_TO_RADIANS(-iAngle), 0.0f, 1.0f, 0.0f); //#define DEGREES_TO_RADIANS(d) (d * M_PI / 180)
yourView.layer.transform = myTransform;
I'll give you the math behind doing it as I don't have code right now to show. Converting finger movement to rotation value is simply a matter of setting up ratios.
For angle value (used in transform):
track_spread rotation_angle
____________ = ______________
movement_x angle = ?
angle = (rotation_angle * movement_x)/track_spread;
WHERE:
track_spread = width_of_your_view (or less e.g. 70% x width_of_your_view)
rotation_angle = the final rotation you want for your view (a constant e.g. 45 degrees)
CGPoint point = [recognizer translationInView:self];
movement_x = abs(point.x);
angle = the value (in degrees) you are interested in and will input into transform after converting to radians
If someone cant figure out and still need code snippet please leave a comment.

Rotating UILabel at its center

I am trying to rotate a UILabel at its center, but when it rotates it changes its position. It doesn't stick to its center. I am using following code to rotate it:
float fromAngle = atan2(m_locationBegan.y-lblText.center.y, m_locationBegan.x-lblText.center.x);
//float toAngle = atan2(_location.y-lblText.center.y, _location.x-lblText.center.x);
float toAngle = atan2(_location.y-lblText.center.y+5, _location.x-lblText.center.x+5);
float newAngle = wrapd(m_currentAngle + (toAngle - fromAngle), 0, 2*3.14);
CGAffineTransform cgaRotate = CGAffineTransformMakeRotation(newAngle);
lblText.transform = cgaRotate;
int oneInFifty = (newAngle*50)/(2*3.14);
NSLog(#"%#",[NSString stringWithFormat:#"fromAngle: %f toAngle: %f Angle: %f 1in50: %i",fromAngle, toAngle, newAngle, oneInFifty]);
Can someone please help me in stopping the center moving from it?
Take a look at this blog post.
Example: (label = UILabel)
// UIView's transform property is a CGAffineTransform.
[UIView beginAnimations:nil context:NULL]; // arguments are optional
view.transform = CGAffineTransformMakeRotation(M_PI_2);
[UIView commitAnimations];
// CALayer's transform property is a CATransform3D.
// rotate around a vector (x, y, z) = (0, 0, 1) where positive Z points
// out of the device's screen.
label.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1);

Rotate a UIImageView around a point off screen? (center of uiImageView

Hi I have a UIImageView which is part on, part off screen.
I want to rotate the view around a point off screen (the center of the view.)
How do I do this?
fullRotationAnimation = [CABasicAnimation animationWithKeyPath:#"transform.rotation"];
fullRotationAnimation.fromValue= [NSNumber numberWithFloat:0.0f];
fullRotationAnimation.toValue = [NSNumber numberWithFloat:2 * M_PI];
fullRotationAnimation.duration = 4;
fullRotationAnimation.repeatCount = 1;
[self->greyRings.layer addAnimation:fullRotationAnimation forKey:#"360"];
I'm using that code at the moment but it just spins it around the center of the screen.
Any ideas please?
Using block animation:
- (void)rotateImageView:(UIImageView *)imageView aroundPoint:(CGPoint)point byAngle:(CGFloat)angle {
CGFloat sinA = sin(angle);
CGFloat cosA = cos(angle);
CGFloat x = point.x;
CGFloat y = point.y;
CGAffineTransform transform = CGAffineTransformMake(cosA,sinA,-sinA,cosA,x-x*cosA+y*sinA,y-x*sinA-y*cosA);
[UIView animateWithDuration:4.0 animations:^{
imageView.transform = transform;
}];
}
Note that angle is in radians, so a full rotation is 2.0*M_PI.
Maybe you have to set anchorPoint of CALayer: see Specifying a Layer’s Geometry for more detail.
//(0,0) is the left-bottom of your layer bounds
self->greyRings.layer.anchorPoint = CGPointMake(0.0f, 0.0f);
I think a negative anchorPoint should also work. So you'd better give your bounds and we can calculate for you.

UIView: rotation + movement

I'm trying to move and rotate a UIImageView. I'm not using Core Animation for this nor I can use it.
By the way, the core part of the animation is what follows:
CGRect r = self.frame;
r.origin.y -= self.gravity + spring;
r.origin.x -= 1;
self.rotation -= 0.015;
self.transform = CGAffineTransformMakeRotation(rotation);
self.frame = r;
It almost works. I does move or it does rotate in place, but when I try to move and rotate it, it completely deforms skewing.
I've tried to move and then rotate and viceversa. I also tried various values for content mode with no luck. Any help?
EDIT
useful tutorial: http://www.permadi.com/blog/2009/05/iphone-sdk-bouncing-and-rotating-ball-example/
It's hard to be sure what's going on without a picture of what you are seeing, but the following may be useful:
When you apply a rotation to a view it rotates it around (0,0), so you need to make sure you set the bounds of your view so that (0,0) is where you want the center of rotation. Suppose the image you are rotating is a 100x200 image and you want to rotate around the center of the image then you would need to say self.bounds = CGMakeRect(-50, -100, 100, 200); If you don't do this it will rotate about it's upper-left corner making sort of a spiral.
Oh, and using self.center to set the view's position seems to be more predictable than using self.frame when you have applied a rotation.
Here's some demo code that might make it easier to understand. In this case the code that does the animation is the view controller, but you should get the idea:
#define USE_SELF_CENTER 0
- (void)viewDidLoad {
[super viewDidLoad];
self.rotation = 0.0f;
self.translation = CGPointMake(self.view.bounds.size.width/2.0f, 0.0);
ObjectView* ov = [[ObjectView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
#if USE_SELF_CENTER==1
ov.center = self.translation;
#else
ov.transform = CGAffineTransformMakeTranslation(self.translation.x, self.translation.y);
#endif
// adjust bounds for center of rotation
ov.bounds = CGRectMake(-50.0f, -50.0f, 100.0f, 100.0f);
[self.view addSubview:ov];
self.objectView = ov;
[ov release];
NSTimer *aTimer = [NSTimer timerWithTimeInterval:0.5 target:self selector:#selector(nextFrame)
userInfo:nil repeats:YES];
self.timer = aTimer;
[aTimer release];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)nextFrame
{
NSLog(#"nextFrame");
self.rotation += (5.0 / 180.0f * M_PI);
self.translation = CGPointMake(self.translation.x, self.translation.y + 2.0);
#if USE_SELF_CENTER==1
CGAffineTransform t = CGAffineTransformMakeRotation(self.rotation);
self.objectView.center = self.translation;
self.objectView.transform = t;
#else
CGAffineTransform rot = CGAffineTransformMakeRotation(self.rotation);
CGAffineTransform txy = CGAffineTransformMakeTranslation(self.translation.x, self.translation.y);
CGAffineTransform t = CGAffineTransformConcat(rot, txy);
self.objectView.transform = t;
#endif
}
The code demonstrates two ways of doing what you want. If USE_SELF_CENTER is zero then all the animation is done via transforms. If USE_SELF_CENTER is non-zero a transform is used for rotation and the translation is accomplished by setting the center of the view.
use something like this, the idea is combine both the transformation i.e.
CGAffineTransform transforms = CGAffineTransformConcat(CGAffineTransformMakeTranslation(-1, -(self.gravity + spring)),CGAffineTransformMakeRotation(rotation));
self.transform = transforms;
Hope this will work
Hello Friend please use this steps. On your XIB, take UIImageView and set Image and set its IBOutlet.
In .h file
int theta;
NSTimer *tmrAnimation;
IBOutlet UIImageView *imgViewLoader;
In .m file
- (void)viewDidLoad
{
[super viewDidLoad];
theta = 0;
tmrAnimation = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:#selector(animationImageViewLoader) userInfo:nil repeats:YES];
}
Add This function in your .m file.
-(void)animationImageViewLoader
{
CGFloat angle = theta * (PI / 100);
CGAffineTransform transform = CGAffineTransformMakeRotation(angle);
theta = (theta + 1) % 200;
imgViewLoader.transform = transform;
}
This code will help for Image Rotation only....
Following code helped me in achieving translation(vertical movement) and rotation together.
CGAffineTransform transform = CGAffineTransformMakeTranslation(0, -200);
transform = CGAffineTransformRotate(transform, M_PI);
[UIView transitionWithView:self
duration:0.5
options:UIViewAnimationOptionAllowAnimatedContent<br>
animations:^{
[view setTransform:transform];
}
completion:^(BOOL finished){
}];
Hope this will help someone else...

zooming from a particular point

I am using this code to zoom from a particular point
CGPoint getCenterPointForRect(CGRect inRect)
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
return CGPointMake((screenRect.size.height-inRect.origin.x)/2,(screenRect.size.width-inRect.origin.y)/2);
}
-(void) startAnimation
{
CGPoint centerPoint = getCenterPointForRect(self.view.frame);
self.view.transform = CGAffineTransformMakeTranslation(centerPoint.x, centerPoint.y);
self.view.transform = CGAffineTransformScale( self.view.transform , 0.001, 0.001);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration];
self.view.transform = CGAffineTransformIdentity;
[UIView commitAnimations];
}
Its not working. What is the correct way to do zooming from a particular point.
I think that, if I've diagnosed your problem correctly, you're getting a scaling animation where the view starts tiny and at a point, then scales and moves to the centre of the screen exactly like you want, but the point it starts at is incorrect?
First of all, views scale around their centre. So if you took out the translation and hence reduced the code you have to:
self.view.transform = CGAffineTransformMakeScale( 0.001, 0.001);
And your view ends up taking up the whole screen then it'll remain centred on the middle of the screen, sort of a little as though it's a long way away and you're heading directly towards it.
Supposing you instead want it to grow and move to the centre of the screen from (x, y) then you need something more like:
CGPoint locationToZoomFrom = ... populated by you somehow ...;
CGPoint vectorFromCentreToPoint = CGPointMake(
locationToZoomFrom.x - self.view.center.x,
locationToZoomFrom.y - self.view.center.y);
self.view.transform = CGAffineTransformMakeTranslation(vectorFromCentreToPoint.x, vectorFromCentreToPoint.y);
self.view.transform = CGAffineTransformScale( self.view.transform , 0.001, 0.001);
Where locationToZoomFrom will be the initial centre of the view and its normal centre as per its frame will be the destination.