旋转UIImageView将图像移开屏幕

时间:2013-06-14 20:06:07

标签: iphone ios objective-c

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

正在旋转中心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;
}

2 个答案:

答案 0 :(得分: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);

但是,在创建this quick project之后,我意识到当你使用UIKit应用旋转变换时(就像你显然那样做),旋转实际上发生在中心周围。只有在使用CoreGraphics时才会在原点周围发生旋转。所以现在我不确定为什么你的图像会从屏幕上消失。无论如何,看看项目,看看有没有任何代码可以帮助你。

如果您还有其他问题,请与我们联系。

使用UIKit绘制'Firefox'图像。使用CoreGraphics绘制蓝色矩形 The 'Firefox' image is drawn using UIKit. The blue rect is drawn using CoreGraphics

答案 1 :(得分:0)

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