簡體   English   中英

如何根據 UIImage 大小調整 UIImageView 的大小並適應屏幕的寬度

[英]How to resize a UIImageView based on UIImage size and fit the screen's width

我有這個代碼片段:

func resizeImageViewToImageSize(_ imageView:UIImageView) {
        let widthRatio = imageView.bounds.size.width / imageView.image!.size.width
        let heightRatio = imageView.bounds.size.height / imageView.image!.size.height
        let scale = min(widthRatio, heightRatio)
        let imageWidth = scale * imageView.image!.size.width
        let imageHeight = scale * imageView.image!.size.height
        print("\(imageWidth) - \(imageHeight)")

        imageView.frame = CGRect(x: 0,
        y: 70,
        width: imageWidth,
        height: imageHeight)
        imageView.center.x = view.center.x
 }

我在viewDidLoad()調用它來調整我originalImageView UIImageView 的大小:

resizeImageViewToImageSize(originalImageView)

它成功地調整了我的 UIImageView 的大小,但如果我從相機(例如在 iPhone7+ 上)拍攝照片,我的 imageWidth 和 imageHeight 是: 226.4 - 283.0 ,這使得我的 UIImageView 在屏幕中央非常小,如下所示:

在此處輸入圖片說明

我想要做的是讓我的originalImageView寬度更大,並相應地保持其縮放比例,如下面的模型,這可能嗎?

在此處輸入圖片說明

我認為當值的問題出現imageView.image!.size.width大於imageView.bounds.size.width或高度值。

這將導致widthRatioheightRatio的值小於1。

scale小於1並乘以imageWidthimageHeight ,最終得到的UIImageView將小於原始圖像。

我猜想像iPhone7一樣,從相機拍攝的圖像的分辨率會很高。

你必須檢查其值越高imageView.bounds.widthimageView.image!.size.width ,然后拿到取決於條件的倒數。

 func resizeImageViewToImageSize(_ imageView:UIImageView) {


    let maxWidth = view.frame.size.width
    let maxHeight = view.frame.size.height

        var widthRatio = imageView.bounds.size.width / imageView.image!.size.width

        if widthRatio < 1 {
            widthRatio = 1 / widthRatio
        }

        let heightRatio = imageView.bounds.size.height / imageView.image!.size.height

        if heightRatio < 1 {
            heightRatio = 1 / widthRatio
        }

        let scale = min(widthRatio, heightRatio)

        let maxWidthRatio = maxWidth / imageView.bounds.size.width
        let maxHeightRatio = maxHeight / imageView.bounds.size.height
        let maxScale = min(maxWidthRatio, maxHeightRatio)

        let properScale = min(scale, maxScale)

        let imageWidth = properScale * imageView.image!.size.width
        let imageHeight = properScale * imageView.image!.size.height
        print("\(imageWidth) - \(imageHeight)")

        imageView.frame = CGRect(x: 0,
        y: 70,
        width: imageWidth,
        height: imageHeight)
        imageView.center.x = view.center.x
 }

您需要將UIImageView的寬度和高度設置為希望它在屏幕上占據的大小,然后將UIImageViewcontentModeUIView.ContentMode.scaleAspectFitUIView.ContentMode.scaleAspectFill ,以使其填充整個屏幕視圖。

https://developer.apple.com/documentation/uikit/uiimageview https://developer.apple.com/documentation/uikit/uiview/contentmode/scaleaspectfit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM