Search code examples
iosobjective-cswiftcashapelayercatransform3d

Rotate a line in ios


I have plus sign which i drawn using lines. Now i want to rotate these lines, so that it will look like a X sign. I tried rotating the lines but no way.

 self.shapeLayer1.transform = CATransform3DMakeRotation( (CGFloat) (GLKMathDegreesToRadians(-45)),0, 0, 0)




 self.shapeLayer2.transform = CATransform3DMakeRotation( (CGFloat) (GLKMathDegreesToRadians(-45)), 0, 0, 0)

You guys can see that, i put zeros in the x, y, z places.!! i tries different values.But colud not get the actual rotation. If somebody got any idea, Please share with me. Sometimes the lines move to another point and rotates.


Solution

  • It looks like the x,y,z parameters define the axis of rotation. Since we want to rotate around xy, your axis of rotation should be the z axis, or 0,0,1.

    self.shapeLayer1.transform = CATransform3DMakeRotation( (CGFloat) (GLKMathDegreesToRadians(45)),0, 0, 1)
    
    self.shapeLayer2.transform = CATransform3DMakeRotation( (CGFloat) (GLKMathDegreesToRadians(-45)), 0, 0, 1)
    

    Regarding the issue you're having with rotation around a non-centerpoint of the line, if you're unable to redraw the line centred around 0,0,0, you can also use the following code to transform it to 0,0,0, rotate, then transform it back to where you need it:

    CGFloat tx = 1.0,ty = 2.0,tz = 0;  // Modify these to the values you need
    CATransform3D t = CATransform3DMakeTranslation (tx, ty, tz);
    t = CATransform3DRotate(t,(CGFloat) (GLKMathDegreesToRadians(45)),0, 0, 1);
    self.shapeLayer1.transform = CATransform3DTranslate(t,-tx,-ty,-tz);
    
    CATransform3D t = CATransform3DMakeTranslation (tx, ty, tz);
    t = CATransform3DRotate(t,(CGFloat) (GLKMathDegreesToRadians(-45)),0, 0, 1);
    self.shapeLayer2.transform = CATransform3DTranslate(t,-tx,-ty,-tz);