ConvertRect会计为UIScrollView缩放和contentOffset

我一直在试图获得一个UIScrollView内的UIView的转换CGRect。 如果我没有放大,它可以正常工作,但是一旦放大,新的CGRect就会移动。 这里是让我closures的代码:

CGFloat zoomScale = (scrollView.zoomScale); CGRect newRect = [self.view convertRect:widgetView.frame fromView:scrollView]; CGPoint newPoint = [self.view convertPoint:widgetView.center fromView:scrollView]; // Increase the size of the CGRect by multiplying by the zoomScale CGSize newSize = CGSizeMake(newRect.size.width * zoomScale, newRect.size.height * zoomScale); // Subtract the offset of the UIScrollView for proper positioning CGPoint newCenter = CGPointMake(newPoint.x - scrollView.contentOffset.x, newPoint.y - scrollView.contentOffset.y); // Create rect with the proper width/height (x and y set by center) newRect = CGRectMake(0, 0, newSize.width, newSize.height); [self.view addSubview:widgetView]; widgetView.frame = newRect; widgetView.center = newCenter; 

我相当肯定,我的问题在于zoomScale – 我可能应该修改基于zoomScale值的x和y坐标。 尽pipe如此,我迄今为止所尝试的一切都是失败的。

我在iOS开发论坛上从用户Brian2012收到以下答案:

我做了什么:

  1. 创build了一个覆盖视图控制器主视图的UIScrollView。
  2. 把一个桌面视图(一个标准的UIView)在滚动视图。 桌面的起源是0,0,尺寸比滚动视图大,所以我可以滚动而不必先放大。
  3. 把一些小部件视图(UIImageView)放到不同位置的桌面视图中。
  4. 将滚动视图的contentSize设置为桌面视图的大小。
  5. 实现viewForZoomingInScrollView作为视图返回桌面视图滚动。
  6. 把NSLogs放在scrollViewDidZoom中,打印出桌面视图的框架和其中一个widget的视图。

我发现:

  1. 小部件框架永远不会改变我设定的初始值。 例如,如果一个小部件从位置108,108开始,大小为64×64,那么无论放大还是滚动,该帧总是被报告为108,108,64,64。
  2. 桌面框架的来源不会改变。 我把桌面的原点置于0,0的滚动视图中,并且始终将原点报告为0,0,无论是放大还是滚动。
  3. 唯一改变的是桌面视图的框架大小,大小只是原始大小乘以滚动视图的缩放比例。

结论:

要找出一个相对于视图控制器主视图坐标系的位置,你需要自己做math运算。 在这种情况下,convertRect方法没有做任何有用的事情。 这里有一些代码尝试

 - (CGRect)computePositionForWidget:(UIView *)widgetView fromView:(UIScrollView *)scrollView { CGRect frame; float scale; scale = scrollView.zoomScale; // compute the widget size based on the zoom scale frame.size.width = widgetView.frame.size.width * scale; frame.size.height = widgetView.frame.size.height * scale; // compute the widget position based on the zoom scale and contentOffset frame.origin.x = widgetView.frame.origin.x * scale - scrollView.contentOffset.x + scrollView.frame.origin.x; frame.origin.y = widgetView.frame.origin.y * scale - scrollView.contentOffset.y + scrollView.frame.origin.y; // return the widget coordinates in the coordinate system of the view that contains the scroll view return( frame ); }