开发者

Orbital Rotation and Transformation of a UIImageView

开发者 https://www.devze.com 2023-03-24 13:00 出处:网络
I have circle that orbits around the center of my view.It continuously rotates 360 degrees.This works fine using my following code:

I have circle that orbits around the center of my view. It continuously rotates 360 degrees. This works fine using my following code:

-(void) rotateGear: (UIImageView*) view angle:(int)angle arc:(float)arc
{
    float x1 = view.frame.origin.x + view.frame.size.width/2;
    float y1 = view.frame.origin.y + view.frame.size.height/2; 
    float radius = sqrtf(powf(160.0f - x1 ,2.0f) + powf(240.0f - y1, 2.0f));

    float x = 160.0f + radius * (cos(arc + M_PI + (angle * (M_PI / 180.0f))));
    float y = 240.0f + radius * (sin(arc + M_PI + (angle * (M_PI / 180.0f))));

    view.frame = CGRectMake(x - view.frame.size.width/2, y - view.frame.size.height/2, view.image.size.width, view.image.size.height);
}

The code above calculates the new position based on the passed in parameters and moves the image to the new location, making it appear as if it's moving in perfect relation to the center of the main view. Everything works perfect.

However, I want to make the view/orb that is orbiting around the center also spin as it rotates. In another timer, I attempt:

littleGear.transform = 
        C开发者_Python百科GAffineTransformRotate(CGAffineTransformIdentity, M_PI * (angle) / 180.0);

Things go crazy. The orb starts flipping, flopping, folding, and bending all around the screen. If I remove the first code, the orbital rotation, it works fine -- it spins perfectly in place.

Essentially, they both work fine until combined and then everything goes nuts. My first guess is that the matrix is getting hosed up with all of the rotation, but I'm not sure how to solve it. Any ideas?


frame is not a stored property of UIView, it is calculated from number of other parameters - view center, bounds, current transform, so if you set nontrivial transformation to your view you no longer can set its frame directly.

In your case as rotating gear is basically just changing its position you can set gear's center instead of frame - that way all view properties should remain in consistent state:

-(void) rotateGear: (UIImageView*) view angle:(int)angle arc:(float)arc
{
    ...    
    view.center = CGPointMake(x, y);
}

P.S. if you want to change view's size as well - change its bounds property instead of frame


I guess that thing would improve if you also did the orbital rotation through a transformation.

What you are looking for in this case is a translation transform:

CGAffineTransform CGAffineTransformMakeTranslation (
  CGFloat tx,
  CGFloat ty
);

that you can the use instead of the CGAffineTransformIdentity when setting littleGear.transform:

 translationTransform = CGAffineTransformMakeTranslation(x, y);
 littleGear.transform = CGAffineTransformRotate(translationTransform, M_PI * (angle) / 180.0);
0

精彩评论

暂无评论...
验证码 换一张
取 消