gpt4 book ai didi

iphone - 应用 CGAffineTransform Rotate 后如何移动 UIImageView?

转载 作者:行者123 更新时间:2023-12-03 19:01:20 26 4
gpt4 key购买 nike

我正在构建一个 iPhone 应用程序。我有一个 UIView,其中包含一组 UIImageView 子类对象。用户可以通过触摸拖动和旋转 ImageView 。旋转 ImageView 后,我在移动 ImageView 时遇到问题。

为了旋转 ImageView ,我应用了变换旋转,效果很好。它看起来像这样:

CGAffineTransform trans = self.transform;
self.transform = CGAffineTransformRotate(trans, delta);

当用户尝试通过触摸移动元素时,问题就会出现。在 TouchesBegan:WithEvent: 中,我将起点保存在类变量 startLocation:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Retrieve the touch point
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
}

在touchesMoved:withEvent:中,我有以下代码,如果 ImageView 上没有旋转变换,它就足够好了:

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPoint pt = [[touches anyObject] locationInView:self];
CGFloat dx = pt.x - startLocation.x;
CGFloat dy = pt.y - startLocation.y;
CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
self.center = newCenter;
}

但是,如果 ImageView 上存在旋转变换,则 ImageView 在每次 TouchMoved 事件上都会在屏幕上晃动,并很快消失。在调试器中,我观察到 pt 的值变得巨大。我突然想到我需要改变这一点,我就这样做了,如下所示:

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
CGPoint pt = [[touches anyObject] locationInView:self];
if (!CGAffineTransformIsIdentity(self.transform)) {
pt = CGPointApplyAffineTransform(pt, self.transform);
}

CGFloat dx = pt.x - startLocation.x;
CGFloat dy = pt.y - startLocation.y;
CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
}

这效果好多了。我现在可以在屏幕上拖动图像。但第一次移动会导致图像在一个方向或另一个方向上晃动一次,具体取决于变换中的旋转角度和 ImageView 的尺寸。

如何在不产生初始晃动的情况下移动 ImageView ?

为什么我不需要转换startLocation(触摸开始时捕获的点)?

最佳答案

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)_event {
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)_event {
CGPoint pt = [[touches anyObject] previousLocationInView:self];
CGFloat dx = pt.x - startLocation.x;
CGFloat dy = pt.y - startLocation.y;
CGPoint newCenter = CGPointMake(self.center.x + dx, self.center.y + dy);
self.center = newCenter;
}

- (void)setRotation:(float)rotation {
self.transform = CGAffineTransformRotate(self.transform, degreesToRadians(rotation));
}

关于iphone - 应用 CGAffineTransform Rotate 后如何移动 UIImageView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4859731/

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