Get scale and rotation angle from CGAffineTransform? - ios

I want to get scale factor and rotation angle form view. I've already applied CGAffineTransform to that view.

The current transformation of an UIView is stored in its transform property. This is a CGAffineTransform structure, you can read more about that here: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGAffineTransform/Reference/reference.html
You can get the angle in radians from the transform like this:
CGFloat angle = atan2f(yourView.transform.b, yourView.transform.a);
If you want the angle in degrees you need to convert it like this:
angle = angle * (180 / M_PI);
Get the scale like this:
CGFloat scaleX = view.transform.a;
CGFloat scaleY = view.transform.d;

I had the same problem, found this solution, but it only partially solved my problem.
In fact the proposed solution for extracting the scale from the transform:
(all code in swift)
scaleX = view.transform.a
scaleY = view.transform.d
only works when the rotation is 0.
When the rotation is not 0 the transform.a and transform.d are influenced by the rotation. To get the proper values you can use
scaleX = sqrt(pow(transform.a, 2) + pow(transform.c, 2))
scaleY = sqrt(pow(transform.b, 2) + pow(transform.d, 2))
note that the result is always positive. If you are also interested in the sign of the scaling (the view is flipped), then the sign of the scaling is the sign of transform.a for x flip and transform.d for y flip. One way to inherit the sign.
scaleX = (transform.a/abs(transform.a)) * sqrt(pow(transform.a, 2) + pow(transform.c, 2))
scaleY = (transform.d/abs(transform.d)) * sqrt(pow(transform.b, 2) + pow(transform.d, 2))

In Swift 3:
let rotation = atan2(view.transform.b, view.transform.a)

Related

How to find X, Y and Rotation value of a UIView after CATransform3D applied

I have a UIView on my screen. I am applying layer.transform to that view with translation and rotation according to users tap movement using tap and rotation gesture. At last i want to retrieve the final x and y position with the rotation separately. Could not find any such post here to get those information from transform. Can anyone help with this?
Here is the code am using to apply the transform.
var transform = CATransform3DIdentity
transform = CATransform3DTranslate(transform, displacementX, displacementY, 1.0)
transform = CATransform3DRotate(transform, gesture.rotation, 0, 0, 1.0)
self.currentItem.imageView.layer.transform = transform
Please refer the following code,
For Applying Transform,
let degrees = 90.0
let radians = CGFloat(degrees * Double.pi / 180)
sampleView.layer.transform = CATransform3DMakeRotation(radians, 0.0, 0.0, 1.0)
To get rotation angle after transform,
let radiansFromSampleView = atan2(sampleView.transform.b, sampleView.transform.a)
let DegreesFromRadiansOFSampleView = CGFloat(180 * Double(radiansFromSampleView) / Double.pi)
For x and y positions you can directly take from frame of the view even after transformation.
Hope this can be helpful.

Get the actual angle after the superview is rotated

I have 5 subviews(White) added to the superview(Gray), when I rotate the superview I want to know the angle(like 1 and 2) of each of the subview with the red circle.(the center of the subviews and the red circle are ON the same circle)
Start Position:
Rotated Position:
From your comment you appear to want to determine the coordinates of the centres of your five circles for a given rotation. The centres will all lie on a circle. So your question boils down to what are the coordinates of a point on a circle of radius r for an angle θ. The parametric equations for a circle give you that:
x = r cos θ
y = r sin θ
The angle, θ, in these equations is measured in radians from the positive x-axis in an anti-clockwise direction. If your angle are in degrees you will find the M_PI constant for π useful as:
360 degrees = 2 π radians
The rest is simple math, take your angle of rotation to give you the angle for A (remembering to adjust for 0 being the x-axis and measuring anti-clockwise if needed), the other centres are multiples of 72 degrees (0.4 π radians) from this.
HTH
I'm not sure I completely understand your question, but if you just need to take a known point and rotate it a certain number of degrees, check out the docs for CGAffineTransform.
For example:
CGAffineTransform rotation = CGAffineTransformMakeRotation (angle);
CGPoint rotatedPoint = CGPointApplyAffineTransform (startingPoint, rotation);
This rotation matrix is around (0, 0) and the angle is in radians, so you will need to subtract the center of your superview's bounds to get an offset relative to the center, do the rotation, and add back in the center. Or you can build an affine transform made up of that translation, rotation, and inverse translation, and then apply that to your starting point as above.
Given that you already seem to know the main rotation angle, this will give you the angles in the range -180 .. +180 and positions of each of the white discs:
GCFloat toRads = M_PI / 180.0;
CGFloat angleA = self.rotationInDegrees;
if (angleA > 180) angleA -= 360;
CGFloat xA = self.radius * sinf(angleA * toRads);
CGFloat yA = self.radius * cosf(angleA * toRads);
CGFloat angleB = angleA + 72;
if (angleB > 180) angleB -= 360;
CGFloat xB = self.radius * sinf(angleB * toRads);
CGFloat yB = self.radius * cosf(angleB * toRads);
etc...
(This assumes your zero degrees is from the vertical. If it's from the horizontal swap cos and sin over).

How to rotate a triangle?

I'm struggling with rotating a triangle resulting from a UIRotationGestureRecognizer. If you could look over my approach and offer suggestions, I'd greatly appreciate it.
I ask the gesture recognizer object for the rotation, which the documentation says is returned in radians.
My strategy had been to think of each vertex as a point on a circle that exists between the center of the triangle and the vertex, and then use the radians of rotation to find the new point on that circumference. I'm not totally sure this is a valid approach, but I wanted to at least try it. Visually I'd know whether or not it was working.
Here's the code I created in that attempt:
- (CGPoint)rotateVertex:(CGPoint)vertex byRadians:(float)radians
{
float deltaX = center.x - vertex.x;
float deltaY = center.y - vertex.y;
float currentAngle = atanf( deltaX / deltaY );
float newAngle = currentAngle + radians;
float newX = cosf(newAngle) + vertex.x;
float newY = sinf(newAngle) + vertex.y;
return CGPointMake(newX, newY);
}
When executed, there's a slight rotation at the beginning, but then as I continue rotating my fingers the vertices just start getting farther away from the center point, indicating I'm confusing something here.
I looked at what the CGContextRotateCTM could do for me, but ultimately I need to know what the vertices are after the rotation, so just rotating the graphics context doesn't appear to leave me with those changed coordinates.
I also tried the technique described here but that resulted in the triangle being flipped about the second vertex, which seems odd, but then that technique works with p and q being the x and y coordinates of the second vertex.
Thanks for taking a look!
Solved: Here is the corrected function. It assumes you have calculated the center of the triangle. I used the 1/3(x1 + x2 + x3), 1/3(y1 + y2 + y3) method described on the Wikipedia article on Centroids.
- (CGPoint)rotatePoint:(CGPoint)currentPoint byRadians:(float)radiansOfRotation
{
float deltaX = currentPoint.x - center.x;
float deltaY = currentPoint.y - center.y;
float radius = sqrtf(powf(deltaX, 2.0) + powf(deltaY, 2.0));
float currentAngle = atan2f( deltaY, deltaX );
float newAngle = currentAngle + radiansOfRotation;
float newRun = radius * cosf(newAngle);
float newX = center.x + newRun;
float newRise = radius * sinf(newAngle);
float newY = center.y + newRise;
return CGPointMake(newX, newY);
}
Of noteworthy relevance to why the first code listing did not work was that the arguments to atan2 were reversed. Also, the correct calculation of the delta values was reversed.
You're forgetting to multiply by the radius of the circle. Also, since the Y axis points down in the UIKit coordinate system, you have to subtract instead of add the radians and negate the y coordinate at the end. And you need to use atan2 only gives output in the range -pi/2 to pi/2:
float currentAngle = atan2f(deltaY, deltaX);
float newAngle = currentAngle - radians;
float radious = sqrtf(powf(deltaX, 2.0) + powf(deltaY, 2.0));
float newX = radius * cosf(newAngle) + vertex.x;
float newY = -1.0 * radius * sinf(newAngle) + vertex.y;
The answer is embedded now in the original question. Gun shy about proper decorum ;-)

Algorithm for creating a circular path around a center mass?

I am attempting to simply make objects orbit around a center point, e.g.
The green and blue objects represent objects which should keep their distance to the center point, while rotating, based on an angle which I pass into method.
I have attempted to create a function, in objective-c, but it doesn't work right without a static number. e.g. (It rotates around the center, but not from the true starting point or distance from the object.)
-(void) rotateGear: (UIImageView*) view heading:(int)heading
{
// int distanceX = 160 - view.frame.origin.x;
// int distanceY = 240 - view.frame.origin.y;
float x = 160 - view.image.size.width / 2 + (50 * cos(heading * (M_PI / 180)));
float y = 240 - view.image.size.height / 2 + (50 * sin(heading * (M_PI / 180)));
view.frame = CGRectMake(x, y, view.image.size.width, view.image.size.height);
}
My magic numbers 160, and 240 are the center of the canvas in which I'm drawing the images onto. 50 is a static number (and the problem), which allows the function to work partially correctly -- without maintaining the starting poisition of the object or correct distance. I don't know what to put here unfortunately.
heading is a parameter that passes in a degree, from 0 to 359. It is calculated by a timer and increments outside of this class.
Essentially what I would like to be able to drop any image onto my canvas, and based on the starting point of the image, it would rotate around the center of my circle. This means, if I were to drop an image at Point (10,10), the distance to the center of the circle would persist, using (10,10) as a starting point. The object would rotate 360 degrees around the center, and reach it's original starting point.
The expected result would be to pass for instance (10,10) into the method, based off of zero degrees, and get back out, (15,25) (not real) at 5 degrees.
I know this is very simple (and this problem description is entirely overkill), but I'm going cross eyed trying to figure out where I'm hosing things up. I don't care about what language examples you use, if any. I'll be able to decipher your meanings.
Failure Update
I've gotten farther, but I still cannot get the right calculation. My new code looks like the following:
heading is set to 1 degree.
-(void) rotateGear: (UIImageView*) view heading:(int)heading
{
float y1 = view.frame.origin.y + (view.frame.size.height/2); // 152
float x1 = view.frame.origin.x + (view.frame.size.width/2); // 140.5
float radius = sqrtf(powf(160 - x1 ,2.0f) + powf(240 - y1, 2.0f)); // 90.13
// I know that I need to calculate 90.13 pixels from my center, at 1 degree.
float x = 160 + radius * (cos(heading * (M_PI / 180.0f))); // 250.12
float y = 240 + radius * (sin(heading * (M_PI / 180.0f))); // 241.57
// The numbers are very skewed.
view.frame = CGRectMake(x, y, view.image.size.width, view.image.size.height);
}
I'm getting results that are no where close to where the point should be. The problem is with the assignment of x and y. Where am I going wrong?
You can find the distance of the point from the centre pretty easily:
radius = sqrt((160 - x)^2 + (240 - y)^2)
where (x, y) is the initial position of the centre of your object. Then just replace 50 by the radius.
http://en.wikipedia.org/wiki/Pythagorean_theorem
You can then figure out the initial angle using trigonometry (tan = opposite / adjacent, so draw a right-angled triangle using the centre mass and the centre of your orbiting object to visualize this):
angle = arctan((y - 240) / (x - 160))
if x > 160, or:
angle = arctan((y - 240) / (x - 160)) + 180
if x < 160
http://en.wikipedia.org/wiki/Inverse_trigonometric_functions
Edit: bear in mind I don't actually know any Objective-C but this is basically what I think you should do (you should be able to translate this to correct Obj-C pretty easily, this is just for demonstration):
// Your object gets created here somewhere
float x1 = view.frame.origin.x + (view.frame.size.width/2); // 140.5
float y1 = view.frame.origin.y + (view.frame.size.height/2); // 152
float radius = sqrtf(powf(160 - x1 ,2.0f) + powf(240 - y1, 2.0f)); // 90.13
// Calculate the initial angle here, as per the first part of my answer
float initialAngle = atan((y1 - 240) / (x1 - 160)) * 180.0f / M_PI;
if(x1 < 160)
initialAngle += 180;
// Calculate the adjustment we need to add to heading
int adjustment = (int)(initialAngle - heading);
So we only execute the code above once (when the object gets created). We need to remember radius and adjustment for later. Then we alter rotateGear to take an angle and a radius as inputs instead of heading (this is much more flexible anyway):
-(void) rotateGear: (UIImageView*) view radius:(float)radius angle:(int)angle
{
float x = 160 + radius * (cos(angle * (M_PI / 180.0f)));
float y = 240 + radius * (sin(angle * (M_PI / 180.0f)));
// The numbers are very skewed.
view.frame = CGRectMake(x, y, view.image.size.width, view.image.size.height);
}
And each time we want to update the position we make a call like this:
[objectName rotateGear radius:radius angle:(adjustment + heading)];
Btw, once you manage to get this working, I'd strongly recommend converting all your angles so you're using radians all the way through, it makes it much neater/easier to follow!
The formula for x and y coordinates of a point on a circle, based on radians, radius, and center point:
x = cos(angle) * radius + center_x
y = sin(angle) * radius + center_y
You can find the radius with HappyPixel's formula.
Once you figure out the radius and the center point, you can simply vary the angle to get all the points on the circle that you'd want.
If I understand correctly, you want to do InitObject(x,y). followed by UpdateObject(angle) where angle sweeps from 0 to 360. (But use radians instead of degrees for the math)
So you need to track the angle and radius for each object.:
InitObject(x,y)
relative_x = x-center.x
relative_y = y-center.y
object.radius = sqrt((relative_x)^2, (relative_y)^2)
object.initial_angle = atan(relative_y,relative_x);
And
UpdateObject(angle)
newangle = (object.initial_angle + angle) % (2*PI )
object.x = cos(newangle) * object.radius + center.x
object.y = sin(newangle) * object.radius + center.y
dx=dropx-centerx; //target-source
dy=-(dropy-centery); //minus = invert screen coords to cartesian coords
radius=sqrt(dy*dy+dx*dx); //faster if your compiler optimizer is bad
if dx=0 then dx=0.000001; //hackpatchfudgenudge*
angle=atan(dy/dx); //set this as start angle for the angle-incrementer
Then go with the code you have and you'll be fine. You seem to be calculating radius from current position each time though? This, like the angle, should only be done once, when the object is dropped, or else the radius might not be constant.
*instead of handling 3 special cases for dx=0, if you need < 1/100 degree precision for the start angle go with those instead, google Polar Arctan.

How can I rotate an UIImageView by 20 degrees?

What do I have to do, if I need to rotate a UIImageView? I have a UIImage which I want to rotate by 20 degrees.
The Apple docs talk about a transformation matrix, but that sounds difficult. Are there any helpful methods or functions to achieve that?
If you want to turn right, the value must be greater than 0 if you want to rotate to the left indicates the value with the sign "-". For example -20.
CGFloat degrees = 20.0f; //the value in degrees
CGFloat radians = degrees * M_PI/180;
imageView.transform = CGAffineTransformMakeRotation(radians);
Swift 4:
let degrees: CGFloat = 20.0 //the value in degrees
let radians: CGFloat = degrees * (.pi / 180)
imageView.transform = CGAffineTransform(rotationAngle: radians)
A transformation matrix is not incredibly difficult. It's quite simple, if you use the supplied functions:
imgView.transform = CGAffineTransformMakeRotation(.34906585);
(.34906585 is 20 degrees in radians)
Swift 5:
imgView.transform = CGAffineTransform(rotationAngle: .34906585)
Swift version:
let degrees:CGFloat = 20
myImageView.transform = CGAffineTransformMakeRotation(degrees * CGFloat(M_PI/180) )
Swift 4.0
imageView.transform = CGAffineTransform(rotationAngle: CGFloat(20.0 * Double.pi / 180))
Here's an extension for Swift 3.
extension UIImageView {
func rotate(degrees:CGFloat){
self.transform = CGAffineTransform(rotationAngle: degrees * CGFloat(M_PI/180))
}
}
Usage:
myImageView.rotate(degrees: 20)
_YourImageView.transform = CGAffineTransformMakeRotation(1.57);
where 1.57 is the radian value for 90 degree
This is an easier formatting example (for 20 degrees):
CGAffineTransform(rotationAngle: ((20.0 * CGFloat(M_PI)) / 180.0))
As far as I know, using the matrix in UIAffineTransform is the only way to achieve a rotation without the help of a third-party framework.

Resources