0

我在我的代码中实现了一个简单的旋转手势,但问题是当我旋转图像时,它总是向右离开屏幕/离开视图。

正在以 X 为中心旋转的图像视图消失或增大(因此它直接从屏幕上移出视图)。

我希望它围绕当前中心旋转,但由于某种原因它正在改变。任何想法是什么原因造成的?

下面的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CALayer *l = [self.viewCase layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:30.0];

    self.imgUserPhoto.userInteractionEnabled = YES;
    [self.imgUserPhoto setClipsToBounds:NO];

    UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationDetected:)];
    [self.view addGestureRecognizer:rotationRecognizer];

    rotationRecognizer.delegate = self;
}

- (void)rotationDetected:(UIRotationGestureRecognizer *)rotationRecognizer
{
    CGFloat angle = rotationRecognizer.rotation;
    self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, angle);
    rotationRecognizer.rotation = 0.0;
}
4

2 回答 2

1

你想围绕它的中心旋转图像,但这不是它实际发生的事情。旋转变换发生在原点周围。所以你要做的是首先应用平移变换将原点映射到图像的中心,然后应用旋转变换,如下所示:

self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, self.imageView.bounds.size.width/2, self.imageView.bounds.size.height/2);

请注意,旋转后,您可能必须撤消平移变换才能正确绘制图像。

希望这可以帮助

编辑:

为了快速回答您的问题,您必须做的是撤消翻译转换,即首先减去您添加到其中的相同差异,例如:

// The next line will add a translate transform
self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, 10, 10);
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, radians);
// The next line will undo the translate transform
self.imageView.transform = CGAffineTransformTranslate(self.imageView.transform, -10, -10);

然而,在创建这个快速项目后,我意识到当您使用 UIKit 应用旋转变换时(就像您显然正在做的那样)旋转实际上发生在中心周围。只有在使用 CoreGraphics 时,才会围绕原点进行旋转。所以现在我不确定你的图像为什么会消失在屏幕上。不管怎样,看看这个项目,看看那里的代码是否对你有帮助。

如果您还有其他问题,请告诉我。

'Firefox' 图像是使用 UIKit 绘制的。蓝色矩形是使用 CoreGraphics 绘制的 'Firefox' 图像是使用 UIKit 绘制的。 蓝色矩形是使用 CoreGraphics 绘制的

于 2013-06-14T20:38:01.973 回答
0

您没有围绕其中心旋转图像。您需要通过将其翻译回正确位置来手动更正

于 2013-06-14T22:56:27.813 回答