将图像大小限制为ScrollView,Swift

时间:2017-08-14 12:30:32

标签: ios swift uiscrollview

我有一个在滚动视图中设置的图像,虽然我已经将scrollView的框架设置为固定的高度和宽度,如下所示,图像超出了边界(见下图)。

如何限制图片以适应scrollView。

imageScrollView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight-50)
imageScrollView.clipsToBounds = true // Has no affect on the image

enter image description here

3 个答案:

答案 0 :(得分:3)

你有对UIImageView的引用吗?如果是,则将其内容模式设置为纵横比较。像这样:

        theImageView.contentMode = .scaleAspectFit

您设置的clipsToBounds只会覆盖父视图边界以外的子视图的任何部分,这就是为什么它不会为您做任何事情。

如果您使用的是Interface Builder,请设置此选项: Interface Builder, baby!

那么,如果你没有对UIImageView的引用怎么办?... 您可以遍历滚动视图的子视图,每当找到UIImageView时,您都可以设置内容模式。类似的东西:

//This is off the top of my head, so my filtering may not be right...
//This is also a one and done solution if you've got a lot of images in your scroll view
for anImgVw in imageScrollView.subviews.filter({$0.isKind(of: UIImageView.self)})
{
    anImgVw.contentMode = .scaleAspectFit
}

否则,我不确定是否可以不引用UIImageView。

答案 1 :(得分:1)

您正在使用的库被编码为与设备方向的缩放相匹配。因此,如果图像方向与视图方向不匹配,最终您的图像在滚动视图中不太合适。

您需要编辑ImageScrollView.swift源文件。假设您使用的是与您提供的链接相同的版本(https://github.com/huynguyencong/ImageScrollView),请更改setMaxMinZoomScalesForCurrentBounds()功能,如下所示:

fileprivate func setMaxMinZoomScalesForCurrentBounds() {
    // calculate min/max zoomscale
    let xScale = bounds.width / imageSize.width    // the scale needed to perfectly fit the image width-wise
    let yScale = bounds.height / imageSize.height   // the scale needed to perfectly fit the image height-wise

    // fill width if the image and phone are both portrait or both landscape; otherwise take smaller scale
    //let imagePortrait = imageSize.height > imageSize.width
    //let phonePortrait = bounds.height >= bounds.width
    //var minScale = (imagePortrait == phonePortrait) ? xScale : min(xScale, yScale)
    //
    // just take the min scale, so the image will completely fit regardless of orientation
    var minScale = min(xScale, yScale)

    let maxScale = maxScaleFromMinScale*minScale

    // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.)
    if minScale > maxScale {
        minScale = maxScale
    }

    maximumZoomScale = maxScale
    minimumZoomScale = minScale * 0.999 // the multiply factor to prevent user cannot scroll page while they use this control in UIPageViewController
}

答案 2 :(得分:0)

您可以使用screenHeight而不是viewHeight

mProjection = ((MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE)).getMediaProjection(permissionsResultCode, permissionsData);