Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a UIView around a center point without rotating the view itself

I would like to rotate a UIView around a center point without rotating the UIView itself. So more like the cars of a ferris wheel (always staying upright) as opposed to the hands of a clock.

The times I've rotated UIViews around a center point, I've used layer position/anchorPoint/transform to accomplish the effect. But that obviously changes the orientation of the view itself.

Any help?

keller

like image 489
Keller Avatar asked Aug 07 '13 19:08

Keller


1 Answers

This is pretty easy to do in Core Animation. I've used some pretty boring static values for this example, so obviously you'll want to make some modifications. But this will show you how to move a view along a circular UIBezierPath.

UIView *view = [UIView new];
[view setBackgroundColor:[UIColor redColor]];
[view setBounds:CGRectMake(0.0f, 0.0f, 50.0f, 50.0f)];
[view setCenter:[self pointAroundCircumferenceFromCenter:self.view.center withRadius:140.0f andAngle:0.0f]];
[self.view addSubview:view];

UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(CGRectGetMidX(self.view.frame) - 140.0f, CGRectGetMidY(self.view.frame) - 140.0f, 280.0f, 280.0f)];

CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 5.0;

pathAnimation.path = [path CGPath];

[view.layer addAnimation:pathAnimation forKey:@"curveAnimation"];

And a basic function to generate the initial center of the view.

- (CGPoint)pointAroundCircumferenceFromCenter:(CGPoint)center withRadius:(CGFloat)radius andAngle:(CGFloat)theta
{
    CGPoint point = CGPointZero;
    point.x = center.x + radius * cosf(theta);
    point.y = center.y + radius * sinf(theta);

    return point;
}
like image 153
Mick MacCallum Avatar answered Nov 09 '22 15:11

Mick MacCallum