如何多次旋转锚点周围的视图

时间:2011-03-15 03:06:16

标签: iphone objective-c cocoa quartz-graphics

我真的很难解决旋转视图时遇到的问题。我试图使几个视图围绕任意点旋转(如触摸)。

首先,没有完全解释(只是接受我的话)我只想说由于我的视图布局的复杂性和我需要完成的东西,“作弊”方法,因为它有时候调用,将所有需要旋转的视图添加到更大的视图并旋转该视图,对我来说不起作用。

我正在更改图层的锚点,以便我的视图将围绕双击点旋转。然而,我无法弄清楚的事情一直让我陷入困境。当我旋转一次(比如说90度),并再次旋转90º,而不是最后180º(你所期望的),我最终达到270º(或其他一些奇怪的数字)。

我会尝试发布足够的代码,以便您可以看到我在说什么(希望能帮助我)。

我在.h

中声明了一个实例变量
UIView *theView;

这是.m(您需要导入QuartzCore框架)

- (void)viewDidLoad {
    [super viewDidLoad];

    theView = [[UIView alloc]initWithFrame:CGRectMake(140, 40, 40, 40)];
    theView.backgroundColor = [UIColor blueColor];

    [self.view addSubview:theView];

}

#define DegreesToRadians(x) ((x) * M_PI / 180.0)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [touches anyObject];

    CGPoint touchLocation = [touch locationInView:self.view];

    if ([touch tapCount]==2) {

        CGFloat xValue = ((touchLocation.x - theView.frame.origin.x)/theView.frame.size.width);
        CGFloat yValue = ((touchLocation.y - theView.frame.origin.y)/theView.frame.size.height);

      CGRect priorRect = theView.frame;
        theView.layer.anchorPoint = CGPointMake(xValue, yValue);
        theView.frame = priorRect;

        static float rotationValue = 0.0f;
        rotationValue += 90.0f;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        theView.transform = CGAffineTransformRotate(theView.transform, DegreesToRadians(rotationValue));
        [UIView commitAnimations];

    }
}

我已经用我可能想到的每种不同配置尝试了这个,所以这个例子就是我扔在一起的原因,因为它看起来非常简洁。无论如何,请帮助我!!!

1 个答案:

答案 0 :(得分:0)

需要正确设置锚点。

Setting anchor point for UIView layer

如果您只想以90度旋转,则不要聚合旋转,它的rotationValue应始终为90度。

如果您希望每次都旋转更多,那么您将遇到跳跃问题,因此您应该看到以下链接,了解如何正确执行此操作。

rotate a UIView around its center but several times

相关问题