如何将UIView缩放(缩放)到给定的CGPoint

13

我花了很多时间尝试使用CGAffineScale将视图转换到给定点,包括围绕锚点移动视图中心并在变换前后移动,并进行全面的搜索。我知道使用UIScrollview会简单得多,但我知道也可以在没有它的情况下实现技术上的可能性,这已经成为我的心头肉。

这个答案非常接近我想要实现的效果,但是该答案仅详细说明了如何通过巧妙地将中心移动到所需缩放位置相对的角落来缩放到给定角落(而不是给定点)。

我应该如何修改mvds的代码以使UIView缩放到UIView中的任何给定点?

CGFloat s = 3;
CGAffineTransform tr = CGAffineTransformScale(self.view.transform, s, s);
CGFloat h = self.view.frame.size.height;
CGFloat w = self.view.frame.size.width;
[UIView animateWithDuration:2.5 delay:0 options:0 animations:^{
    self.view.transform = tr;
    self.view.center = CGPointMake(w-w*s/2,h*s/2);
} completion:^(BOOL finished) {}];
2个回答

6

这里有两个步骤:首先,你需要将要缩放的视图进行扩大。然后,设置这个被扩大的视图的中心点使得你想要观察的部分最终出现在视图的正中间。

你可以在纸上画出图形,公式随之而来(未经测试)。

CGFloat s = 3;
CGPoint p = CGPointMake(100, 200);
CGAffineTransform tr = CGAffineTransformScale(self.view.transform, s, s);
CGFloat h = self.view.frame.size.height;
CGFloat w = self.view.frame.size.width;
[UIView animateWithDuration:2.5 delay:0 options:0 animations:^{
    self.view.transform = tr;
    CGFloat cx = w/2-s*(p.x-w/2);
    CGFloat cy = h/2-s*(p.y-h/2);
    self.view.center = CGPointMake(cx, cy); //was: (w*s/2,h-h*s/2);
} completion:^(BOOL finished) {}];

2
非常感谢您的回答。我确实尝试过这个方法,但它仍然会缩放到错误的点。我也尝试在纸上画图,但逻辑仍然困扰着我。 - glenstorey

4

我自己也遇到了这个问题。为了解决它,我只需要改变我正在缩放的视图的锚点,因为CGAffineTransform是以视图的锚点为基准进行操作的,所以根据锚点的位置,变换将以不同的方式对视图进行缩放、平移或旋转。以下是基本思路:

CGPoint pointToScaleTo = CGPointMake(x, y); //Just enter the coordinates you 
                                            //want to scale your view towards

CGFloat viewWidth = self.view.bounds.size.width;
CGFloat viewHeight = self.view.bounds.size.height;

CGFloat scaleFactorX = ...;
CGFloat scaleFactorY = ...;

CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scaleFactorX, scaleFactorY);

[UIView animateWithDuration:2.5f delay:0.0f options:0 animations:^{

    //I divide the x and y coordinates by the view width and height
    //because the anchor point coordinates are normalized to the range
    //0.0-1.0.
    self.view.layer.anchorPoint = CGPointMake(pointToScaleTo.x/viewWidth, pointToScaleTo.y/viewHeight);

    //Now that the anchor point has been changed, apply the scale transform
    self.view.layer.transform = scaleTransform;

} completion:^(BOOL finished) {}];

1
感谢您的回答。由于iOS7(我想是这个原因),我将CGAffineTransform行更改为CATransform3D scaleTransform3D = CATransform3DMakeScale(scaleFactorX, scaleFactorY, 1.0);(view.layer.transform必须是CATransform3D)。现在发生的情况是视图跳转,以便pointToScaleTo位于中心(这不是理想的 - 理想情况下,我希望缩放到该点而不是跳转到该点,然后缩放),然后旋转-90º。我不确定我从哪里得到旋转。您知道如何使其缩放到该点而不是跳转然后缩放吗? - glenstorey
你可以使用 self.view.layer.transform = CATransform3DMakeAffineTransform(scaleTransform); 将仿射变换转换为 CATransform3D - Dennis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接