Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to rotate a CGPoint on a grid?

I want to rotate a CGPoint on the screen depending on the angle and the rotation is anchored on another point. Was wondering what is the most efficient way of doing this?

like image 648
Frank Avatar asked Oct 20 '09 15:10

Frank


3 Answers

You can also use that:

rotatedPoint = CGPointApplyAffineTransform(initialPoint, CGAffineTransformMakeRotation(angle));

EDIT: to perform rotation around custom point you must do like Adam described in his answer. Using CGAffineTransform it must look something like:

CGAffineTransform translateTransform = CGAffineTransformMakeTranslation(customCenter.x, customCenter.y);
CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(angle);

CGAffineTransform customRotation = CGAffineTransformConcat(CGAffineTransformConcat( CGAffineTransformInvert(translateTransform), rotationTransform), translateTransform);

rotatedPoint = CGPointApplyAffineTransform(initialPoint, customRotation);
like image 56
Vladimir Avatar answered Nov 19 '22 09:11

Vladimir


Use a 2D rotation matrix. If you want to rotate a point counterclockwise about the origin by an angle of angle, then you would do this:

CGPoint RotatePointAboutOrigin(CGPoint point, float angle)
{
    float s = sinf(angle);
    float c = cosf(angle);
    return CGPointMake(c * point.x - s * point.y, s * point.x + c * point.y);
}

If you want to rotate about a point other than the origin, you'll have to first subtract the center of rotation from your point, rotate it using the above, and then add back in the center of rotation (this is called conjugation in matrix theory).

like image 13
Adam Rosenfield Avatar answered Nov 19 '22 08:11

Adam Rosenfield


Swift 5

extension CGPoint {
    func rotate(around center: CGPoint, angle: CGFloat) -> CGPoint {
        let translate = CGAffineTransform(translationX: -center.x, y: -center.y)
        let transform = translate.concatenating(CGAffineTransform(rotationAngle: angle))
        let rotated = applying(transform)
        return rotated.applying(CGAffineTransform(translationX: center.x, y: center.y))
    }
}
like image 2
Thompsonmachine Avatar answered Nov 19 '22 09:11

Thompsonmachine