UIImageView/UIScrollView强制固定的宽高比适合屏幕

Ale*_*xFZ 10 iphone uiscrollview ipad ios

我正在为iPad制作一个简单的应用程序,它包含一个可以放大/缩小并导航的巨型图像.

这张图片放在a里面UIImageView,然后放在里面UIScrollView.

导航和缩放工作100%罚款; 但是,图像以固定的宽高比加载以适合屏幕,并且永远不会改变(即使在放大时).

我有一种感觉,Interface Builder正在设置一些我不知道的属性,但我已经尝试了一些我能想到的解决这个问题的方法.

问题:

当应用程序最初加载时,其中的内容UIScrollView会自动调整大小,以便通过更改其宽高比来完全适合iPad屏幕./fixed; 实际图像很大(比iPad分辨率大).即使放大图像,此缩放的宽高比仍然保持不变,并使图像看起来拉伸.

无论我尝试什么,我都无法阻止iPad自动重新缩放我的图片.我只是希望应用程序开始与我的形象在iPad上正常显示(100%缩放),与目前适合iPad的屏幕为图像的左上角上的部分.

我试图解决它:

我尝试将UIImageView'sInterface Builder中的内容模式更改为"左上角".这似乎工作得很好,但后来我意识到,UIScrollView不会让你滚动图像经过最初显示的部分(左上角).您可以放大左上角并滚动,但不要超过最初在屏幕上显示的内容.

码:

这是我用来设置视图的代码.imageScrollViewUIScrollView,而且imageViewUIImageView.他们都是IBOutlets.

   // Set the needed attributes of the imageView
    [imageView setImage:[UIImage imageNamed: @"TestImage.png"]];
    imageView.userInteractionEnabled = YES;

    // Set a bunch of the imageScrollView attributes.

    // calculate minimum scale to perfectly fit image width, and begin at that scale
    float minimumScale = [imageScrollView frame].size.width  / [imageView frame].size.width;
    [imageScrollView setMinimumZoomScale:minimumScale];
    [imageScrollView setZoomScale:1];
    [imageScrollView setMaximumZoomScale:10];
    [imageScrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)];
    [imageScrollView setScrollEnabled:YES];
    [imageScrollView setUserInteractionEnabled:YES];
    imageScrollView.clipsToBounds = YES;
    imageScrollView.bounces = FALSE;
    imageScrollView.bouncesZoom = FALSE;
Run Code Online (Sandbox Code Playgroud)

我也有两个UIGestureRecongizers处理分接头缩放,但我不相信它们是问题.当我评论它们时,没有任何改变.

任何帮助将非常感激.

Ale*_*xFZ 16

我修好了它!

对于其他任何有相同问题的人,以下是我修复代码的方法:

错误的原因是Interface Builder强制视图使用ScaleToFill contentMode.将ScrollView'scontentMode 设置为UIViewContentModeScaleAspectFit不能自行运行,因为它imageView仍然被扭曲.

修复:

下面的代码具有在设置为的端部要被添加UIScrollViewUIImageView(内部的viewDidLoad()方法):

    [imageScrollView setContentMode:UIViewContentModeScaleAspectFit];
    [imageView sizeToFit];
    [imageScrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)];
Run Code Online (Sandbox Code Playgroud)

说明:

首先,UIScrollView's contentMode设置为AspectFit,像@Mike建议的那样.然后,调用sizeToFit()imageView来覆盖Interface Builder令人讨厌的预设,并使图像的大小正确.

最后一行非常重要.您必须contentSize重新调整大小后设置ScrollView imageView.否则,ScrollView会认为图像仍然是iPad显示屏的大小,因此不会认为有任何可滚动的内容.设置调整大小和更改ScrollView 后的大小会使图像的实际大小.ImageViewScrollView's contentModeScrollView

希望有所帮助!

感谢Mike的帮助,它让我走上正轨:)

  • 亚历克斯

  • 在关闭主视图退出滚动的ChildBrowser之后,我遇到了这个问题.我用这个技巧恢复主视图上的滚动. (2认同)