首页 文章

iPhone:如何仅从scrollview中缩放图像

提问于
浏览
0

我有ScrollView zoom这个问题 . 有很多关于它的文章,但不知怎的,我找不到正确的解释,教程或代码片段 .

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

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

任何帮助欢迎..

2 回答

  • 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];
    
  • 0

    来自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;
    

    这对于仅缩放图像无效,但至少在缩放时它会保持居中 .

相关问题