1

我将 UIImageView 放在 UIScrollView 中,并尝试控制图像,使其在缩放后以滚动视图为中心。而且我不确定最好的方法。

苹果文档告诉我们不要使用框架属性:“警告如果变换属性不是恒等变换,则此属性的值未定义,因此应被忽略。” 所以我尝试在 UIViewController 子类中使用以下内容,该子类的 xib 包含一个 scrollView 并包含 imageView:

scrollView.bounds =
    CGRectMake 
    (scrollView.contentSize.width/2 - scrollView.center.x,
     scrollView.contentSize.height/2 - scrollView.center.y,
     scrollView.bounds.size.width,
     scrollView.bounds.size.height);

containedView.center =    
    CGPointMake 
    (containedView.bounds.size.width*scrollView.zoomScale/2,
     containedView.bounds.size.height*scrollView.zoomScale/2);

这可以在 containsView 的宽度和高度大于 scrollView 的情况下准确地工作,并设置视图以便后续滚动将您准确地带到 containsView 的边缘。但是,当图像的任一尺寸小于 scrollView 的宽度和高度时,图像会被磁性吸引到屏幕的左上角。在 iPad 模拟器中(仅),当图像缩小到 minimumZoom 的大小时,它会锁定到屏幕的中心。磁吸引力非常平滑,就像在图像居中后 UI 中的某些内容覆盖了我的代码一样。它看起来有点像 CALayer contentsGravity ( kCAGravityTopLeft ) 的东西,也许吧?

Apple 在他们的代码示例 photoScroller(在 UIScrollView 的子类中)中反驳了他们自己的建议:

// center the image as it becomes smaller than the size of the screen

CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = imageView.frame;

// center horizontally
if (frameToCenter.size.width < boundsSize.width)
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
    frameToCenter.origin.x = 0;

// center vertically
if (frameToCenter.size.height < boundsSize.height)
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
    frameToCenter.origin.y = 0;

imageView.frame = frameToCenter;

当图像较小时,此方法可以更好地居中,但是当我在我的项目中尝试此方法时,它会引入某种不一致。例如,在 scrollView.bounces = NO 的情况下,高度小于 scrollView 高度但宽度更大(因此可以从左到右滚动)的水平图像将比它应该向左滚动更远(当向右滚动它会在图像的边缘正确停止,尽管如果 scrollView.bounces = YES 它会从边缘反弹,因此图像总是在左侧裁剪)当图像在两个维度上都大于其包含的滚动视图时这个问题更加突出,整个结果让人感觉很糟糕,考虑到苹果的书面建议,这并不奇怪。

我已经搜索了论坛,但找不到太多关于此的评论。我错过了一些非常明显的东西吗?

4

1 回答 1

0

您似乎没有使用transform属性,因此您可以忽略有关在使用 transform 属性时不使用 frame 属性的警告。继续使用 frame 属性,就像 Apple(和我们其他人)一样。

于 2012-05-04T22:09:08.693 回答