gpt4 book ai didi

iphone - 旋转 UIImageView 将图像移出屏幕

转载 作者:行者123 更新时间:2023-11-29 03:50:41 27 4
gpt4 key购买 nike

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

以X为中心旋转的 ImageView 会偏离或增大(因此它会直接从屏幕上移出 View )。

我希望它围绕当前中心旋转,但由于某种原因它正在发生变化。你知道是什么原因造成的吗?

代码如下:

- (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;
}

最佳答案

您想要围绕图像中心旋转图像,但这并不是实际发生的情况。旋转变换围绕原点进行。因此,您要做的就是首先应用平移变换将原点映射到图像的中心,然后应用旋转变换,如下所示:

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 时,旋转才会围绕原点发生。所以现在我不确定为什么你的图像会从屏幕上消失。不管怎样,看看这个项目,看看那里的代码是否对你有帮助。

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

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

关于iphone - 旋转 UIImageView 将图像移出屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17116459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com