我花了很多时间试图找到一种方法来使用CGAffineScale将视图转换为给定点,包括弄乱锚点,在转换之前和之后移动视图的中心以及全面的Google搜索。我知道使用UIScrollview会更简单;但我知道技术上可以不用一个,而且它在我脑海中成为一个分裂。
This answer非常接近我想要实现的目标,但答案只是通过巧妙地将中心移动到与中心相对的角落来提供有关如何缩放到给定角落(而不是给定点)的详细信息。你想放大。
如何修改mvds' code以将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) {}];
答案 0 :(得分: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) {}];
答案 1 :(得分:3)
我实际上遇到了同样的问题。为了解决这个问题,我所做的就是更改我正在缩放的视图的锚点,因为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) {}];