How to set UIView rotation by degrees - ios

I'm trying to reflect accelerometer data in an iOS app by rotating a UIImageView object. Currently, I am rotating the object based on the difference between its current position reading and the previous position reading (e.g. if the accelerometer was at 90 degrees and is now at 80 degrees it will rotate the object -10 degrees). This method has issues though because there are unread changes in the accelerometer.
As such, I want to set the rotation of the UIImageView based on the degree orientation of the accelerometer. For example, if the accelerometer reads at 65 degrees, I want to set the orientation of the UIImageView object to 65 degrees. Is there a way to do this?
Furthermore, I would like for the rotation to be animated.
Here is my current code which rotates the image view object based on the change from the previous reading:
// UIImage view declaration
#IBOutlet weak var visualizer: UIImageView!
// Rotation code where 'deg' is the change in rotation from the previous reading
UIView.animate(withDuration: 1.0, delay: 0, options: .curveLinear, animations: { () -> Void in self.visualizer.transform = self.visualizer.transform.rotated(by: CGFloat(truncating: deg))})
Note that I would change another part of my code so that 'deg' would be the orientation of the accelerometer in degrees instead of the change in degrees.

the rotation is based on Radian, so you just need to do the math
let radian = degree * CGFloat.pi / 180
to rotate object to n degree use CGAffineTransform
view.transform = CGAffineTransform(rotationAngle: (degree * CGFloat.pi / 180))

Related

Calculate Image Rotation - (0° 360°)

I'd like to calculate the rotation of an image in degrees (calculate affine transformation ) .
This is what I got so far:
extension Double {
var toDegrees: Double { return self * 180 / .pi }
}
let rotationAngle = Double(atan2f(Float(self.myView.transform.b), Float(self.myView.transform.a))).toDegrees
print(rotationAngle)
The "rotationAngle" I'm getting looks quite good but tbh I't is not:
But if I rotate the image about 0° or about 180° I get the same values (same for rotating the image about 90° && -90° --> values are both 45°):
EDIT: This is how I can apply rotation on my imageView:
self.ImageView.transform = CGAffineTransform(rotationAngle: CGFloat(.pi))
How can I fix this to get a unique value for every rotation angle? (0° - 360°).
EDIT:
See some more rotations (the first value is the degree value I've turned the image, the second one is the calculated rotationAngle):
EDIT 2:
0° --> rotationAngle: 0.249977666546474, transform.b: 0.004362960593833, transform.a: 0.999990482242134
-90° --> rotationAngle: -44.999557289943, transform.b: -0.999984511428548, transform.a: 0.00556568980525373
180° --> rotationAngle: 0.0352338243182017, transform.b: 0.00061494629500543, transform.a: -0.999999810920509
90° --> rotationAngle: 44.9995128937134, transform.b: 0.99998300906796, transform.a: -0.00582937178330692

Rotate camera around itself

I am using two virtual joysticks to move my camera around the scene. The left stick controls the position and the right one controls the rotation.
When using the right stick, the camera rotates, but it seems that the camera rotates around the center point of the model.
This is my code:
fileprivate func rotateCamera(_ x: Float, _ y: Float)
{
if let cameraNode = self.cameraNode
{
let moveX = x / 50.0
let rotated = SCNMatrix4Rotate(cameraNode.transform, moveX, 0, 1, 0)
cameraNode.transform = rotated
}
}
I have also tried this code:
fileprivate func rotateCamera(_ x: Float, _ y: Float)
{
if let cameraNode = self.cameraNode
{
let moveX = x / 50.0
cameraNode.rotate(by: SCNQuaternion(moveX, 0, 1, 0), aroundTarget: cameraNode.transform)
}
}
But the camera just jumps around. What is my error here?
There are many ways to handle rotation, some are very suitable for giving headaches to the coder.
It sounds like the model is at 0,0,0, meaning it’s in the center of the world, and the camera is tranformed to a certain location. In the first example using matrices, you basically rotate that transformation. So you transform first, then rotate, which yes will cause it to rotate around the origin (0,0,0).
What you should do instead, to rotate the camera in local space, is rotate the camera first in local space and then translate it to its position in world space.
Translation x rotation matrix results in rotation in world space
Rotation x translation matrix results in rotation in local space
So a solution is to remove the translation from the camera first (moving it back to 0,0,0), then apply the rotation matrix, and then reapply the translation. This comes down to the same result as starting with an identity matrix. For example:
let rotated = SCNMatrix4Rotate(SCNMatrixIdentity, moveX, 0, 1, 0)
cameraNode.transform = SCNMatrix4Multiply(rotated, cameraNode.transform)

CGAffineTransfrom: Translating after a rotation

I am trying to animate a rectangle after I have rotated it with CGAffineTransform. The issue I am having is that the rectangle ends up where it is suppose to be, but the "starting" position for the second transform is not what I expect. This is only an issue because I am animating it. Here is my code below:
UIView.animate(withDuration: 5) {
let shift = 200 * CGFloat(2.0.squareRoot() / 2)
view.transform = view.transform.translatedBy(x: shift, y: 0)
}
view is already defined elsewhere and I have already rotated the view with this:
let rotation = CGAffineTransform(rotationAngle: (45/180)*CGFloat(M_PI))
view.transform = rotation
Before the animation, this is what it looks like: 1
For some reason, the transformation starts above (a little offscreen) and then moves down into position. 2
I would like this to happen instead, where it starts from the original picture, and then shifts in the direction of how its rotated. 3
Note I did try to apply the same shift value to both x and y for the translation but that did not fix my issue.

How to do transforms on a CALayer?

Before writing this question, I've
had experience with Affine transforms for views
read the Transforms documentation in the Quartz 2D Programming Guide
seen this detailed CALayer tutorial
downloaded and run the LayerPlayer project from Github
However, I'm still having trouble understanding how to do basic transforms on a layer. Finding explanations and simple examples for translate, rotate and scale has been difficult.
Today I finally decided to sit down, make a test project, and figure them out. My answer is below.
Notes:
I only do Swift, but if someone else wants to add the Objective-C code, be my guest.
At this point I am only concerned with understanding 2D transforms.
Basics
There are a number of different transforms you can do on a layer, but the basic ones are
translate (move)
scale
rotate
To do transforms on a CALayer, you set the layer's transform property to a CATransform3D type. For example, to translate a layer, you would do something like this:
myLayer.transform = CATransform3DMakeTranslation(20, 30, 0)
The word Make is used in the name for creating the initial transform: CATransform3DMakeTranslation. Subsequent transforms that are applied omit the Make. See, for example, this rotation followed by a translation:
let rotation = CATransform3DMakeRotation(CGFloat.pi * 30.0 / 180.0, 20, 20, 0)
myLayer.transform = CATransform3DTranslate(rotation, 20, 30, 0)
Now that we have the basis of how to make a transform, let's look at some examples of how to do each one. First, though, I'll show how I set up the project in case you want to play around with it, too.
Setup
For the following examples I set up a Single View Application and added a UIView with a light blue background to the storyboard. I hooked up the view to the view controller with the following code:
import UIKit
class ViewController: UIViewController {
var myLayer = CATextLayer()
#IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// setup the sublayer
addSubLayer()
// do the transform
transformExample()
}
func addSubLayer() {
myLayer.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
myLayer.backgroundColor = UIColor.blue.cgColor
myLayer.string = "Hello"
myView.layer.addSublayer(myLayer)
}
//******** Replace this function with the examples below ********
func transformExample() {
// add transform code here ...
}
}
There are many different kinds of CALayer, but I chose to use CATextLayer so that the transforms will be more clear visually.
Translate
The translation transform moves the layer. The basic syntax is
CATransform3DMakeTranslation(_ tx: CGFloat, _ ty: CGFloat, _ tz: CGFloat)
where tx is the change in the x coordinates, ty is the change in y, and tz is the change in z.
Example
In iOS the origin of the coordinate system is in the top left, so if we wanted to move the layer 90 points to the right and 50 points down, we would do the following:
myLayer.transform = CATransform3DMakeTranslation(90, 50, 0)
Notes
Remember that you can paste this into the transformExample() method in the project code above.
Since we are just going to deal with two dimensions here, tz is set to 0.
The red line in the image above goes from the center of the original location to the center of the new location. That's because transforms are done in relation to the anchor point and the anchor point by default is in the center of the layer.
Scale
The scale transform stretches or squishes the layer. The basic syntax is
CATransform3DMakeScale(_ sx: CGFloat, _ sy: CGFloat, _ sz: CGFloat)
where sx, sy, and sz are the numbers by which to scale (multiply) the x, y, and z coordinates respectively.
Example
If we wanted to half the width and triple the height, we would do the following
myLayer.transform = CATransform3DMakeScale(0.5, 3.0, 1.0)
Notes
Since we are only working in two dimensions, we just multiply the z coordinates by 1.0 to leave them unaffected.
The red dot in the image above represents the anchor point. Notice how the scaling is done in relation to the anchor point. That is, everything is either stretched toward or away from the anchor point.
Rotate
The rotation transform rotates the layer around the anchor point (the center of the layer by default). The basic syntax is
CATransform3DMakeRotation(_ angle: CGFloat, _ x: CGFloat, _ y: CGFloat, _ z: CGFloat)
where angle is the angle in radians that the layer should be rotated and x, y, and z are the axes about which to rotate. Setting an axis to 0 cancels a rotation around that particular axis.
Example
If we wanted to rotate a layer clockwise 30 degrees, we would do the following:
let degrees = 30.0
let radians = CGFloat(degrees * Double.pi / 180)
myLayer.transform = CATransform3DMakeRotation(radians, 0.0, 0.0, 1.0)
Notes
Since we are working in two dimentions, we only want the xy plane to be rotated around the z axis. Thus we set x and y to 0.0 and set z to 1.0.
This rotated the layer in a clockwise direction. We could have rotated counterclockwise by setting z to -1.0.
The red dot shows where the anchor point is. The rotation is done around the anchor point.
Multiple transforms
In order to combine multiple transforms we could use concatination like this
CATransform3DConcat(_ a: CATransform3D, _ b: CATransform3D)
However, we will just do one after another. The first transform will use the Make in its name. The following transforms will not use Make, but they will take the previous transform as a parameter.
Example
This time we combine all three of the previous transforms.
let degrees = 30.0
let radians = CGFloat(degrees * Double.pi / 180)
// translate
var transform = CATransform3DMakeTranslation(90, 50, 0)
// rotate
transform = CATransform3DRotate(transform, radians, 0.0, 0.0, 1.0)
// scale
transform = CATransform3DScale(transform, 0.5, 3.0, 1.0)
// apply the transforms
myLayer.transform = transform
Notes
The order that the transforms are done in matters.
Everything was done in relation to the anchor point (red dot).
A Note about Anchor Point and Position
We did all our transforms above without changing the anchor point. Sometimes it is necessary to change it, though, like if you want to rotate around some other point besides the center. However, this can be a little tricky.
The anchor point and position are both at the same place. The anchor point is expressed as a unit of the layer's coordinate system (default is 0.5, 0.5) and the position is expressed in the superlayer's coordinate system. They can be set like this
myLayer.anchorPoint = CGPoint(x: 0.0, y: 1.0)
myLayer.position = CGPoint(x: 50, y: 50)
If you only set the anchor point without changing the position, then the frame changes so that the position will be in the right spot. Or more precisely, the frame is recalculated based on the new anchor point and old position. This usually gives unexpected results. The following two articles have an excellent discussion of this.
About the anchorPoint
Translate rotate translate?
See also
Border, rounded corners, and shadow on a CALayer
Using a border with a Bezier path for a layer

How to make a node to rotate around a point outside of the node in a spritekit game project

I came across this answer, but the answer is not clear to me. Can someone provide some sample code?
Create an SKNode and set its position to the center of rotation. Add the node that should rotate around that center as child to the center node. Set the child node's position to the desired offset (ie radius, say x + 100). Change the rotation property of the center node to make the child node(s) rotate around the center point.
Specifically, "Change the rotation property of the center node" to what?
var centerNode: SKSpriteNode = SKSpriteNode(imageNamed: "image1")
centerNode.position = CGPointMake(self.frame.width/2, self.frame.height/2)
self.addChild(centerNode)
var nodeRotateMe: SKSpriteNode = SKSpriteNode(imageNamged: "image2")
nodeRotateMe.position = CGPointMake(self.frame.width/2 + 100, self.frame.height/2 + 100)
centerNode.addChild(nodeRotateMe)
// Change the rotation property of the center node to what??
centerNode.zRotation = ?
You have a couple of options:
1) You could rotate the centerNode over time in your SKScene's update: method by changing its zRotation property manually. You'll have to change the value slowly, at every call to update: to achieve a gradual rotation.
Note that the zRotation property is in radians, with means a 180 degree rotation would be equal to pi (M_PI). SKScene strives to update: at 60 FPS, which means to rotate 360 degrees over 5 seconds, you'd need to increment by 1/300th of a degree every call to update, which would be 1/150th of pi every update.
centerNode.zRotation = centerNode.zRotation + CGFloat(1.0/150.0 * M_PI)
Of course, there is no guarantee that your scene will be able to update at 60 FPS, so you may have to monitor the currentTime variable in update: and adjust accordingly.
2) Probably better, you could use an SKAction to rotate the centerNode for you.
let rotateAction = SKAction.rotateByAngle(CGFloat(2 * M_PI), duration: 5.0)
centerNode.runAction(rotateAction)
Note that the rotation angle is in radians, not degrees. Also note that the centerNode need not be a Sprite Node if you don't want to display an image there; it could be a regular SKNode.

Resources