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) {}];
4

2 回答 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) {}];
于 2013-08-23T07:47:50.823 回答
4

实际上,我自己也遇到了同样的问题。为了解决这个问题,我所做的只是更改了我正在缩放的​​视图的锚点,因为 CGAffineTransforms 是在相对于其锚点的视图上执行的,因此根据锚点的位置,变换将缩放、平移或旋转看法不同。这是基本思想:

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) {}];
于 2013-09-18T04:10:06.963 回答