【问题标题】:iPhone: how to zoom only the image from scrollviewiPhone:如何仅缩放滚动视图中的图像
【发布时间】:2010-12-06 10:04:25
【问题描述】:

我在使用 ScrollView 缩放时遇到了这个问题。有很多关于它的文章,但不知何故我找不到正确的解释、教程或代码 sn-p。

我有全屏滚动视图和全屏图像视图。在 imageview 中,我加载 AspectFit 图像(它们可以是垂直的或水平的,水平的图像上方和下方都有黑色空间)。当我进行缩放时,我不仅会缩放图像,还会缩放周围的区域(图像视图的其余部分)。此外,当我在缩放时旋转模拟器时,图像会转到右上角,而不是像开始时那样居中。甚至很少有像素会超出屏幕范围。

我真的很想只缩放图像而不是整个图像视图,或者至少在缩放时始终使图像居中。

欢迎任何帮助..

【问题讨论】:

    标签: iphone xcode image uiscrollview


    【解决方案1】:

    我解决了这个问题,它不是最好的代码,但现在对我来说很好,我可能会稍后清理它。在这里发帖,也许会对某人有所帮助:)

    UIImage *img = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] 
                                       pathForResource:someImage ofType:@"jpg"]];
    CGFloat scale; 
        if (scrollView.frame.size.width < scrollView.frame.size.height) // portrait
            scale = scrollView.frame.size.width / img.size.width;
        if (scrollView.frame.size.width > scrollView.frame.size.height) // landscape
            scale = scrollView.frame.size.height / img.size.height;
    
    imgView.frame = CGRectMake(scrollView.frame.origin.x, scrollView.frame.origin.y, 
                               img.size.width*scale, img.size.height*scale);
    imgView.center = CGPointMake(scrollView.frame.size.width/2, scrollView.frame.size.height/2);
    
    [imgView setImage:img];
    
    [scrollView setZoomScale:scale];
    

    【讨论】:

      【解决方案2】:

      来自 PhotoScroller 示例;将此添加到 layoutSubviews:

      // 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;
      

      这对仅缩放图像没有帮助,但至少在您缩放时它会保持居中。

      【讨论】:

      • 我应该把它放在哪里? :) 我只是用 imgView.image = [UIImage imageNamed:whichNext];我并没有真正用图像初始化任何矩形。我只是改变了imageView的内容。
      • 你可以把它放在 layoutSubviews 中 - 如果你在创建 UIImageView 的框架时不初始化它,它会占用你初始化它的图像的大小(尽管如果你给它具有新尺寸的不同图像,您应该调用[sizeToFit] 来调整它)。正如您在上面看到的,在这种情况下您也没有改变它的大小;你只是在改变它的原点,所以当你缩小时它会居中。
      猜你喜欢
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多