简体   繁体   中英

Swift scaleAspectFill only width

I have got a UIImageView in Swift

let background_image: UIImageView = {
    let v = UIImageView()
    v.image = #imageLiteral(resourceName: "basketball")
    v.contentMode = .scaleToFill
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

What i want to do here is to have the image fill the background without getting smaller or bigger. Imagine this image is the background 在此处输入图片说明

What I want to do is to get the 100x100 px of this image and show only that. Just like in this image.

You have to set two properties of UIImageView.

Programmatically:

imgView.contentMode = .center
imgView.clipsToBounds = true

If you are using Storyboard, then you can set directly:

在此处输入图片说明

For crop the image from center you have to set the content mode to center and allow image to clips to bound which prevent image view size

imageView.contentMode = .center /* take center part of image*/
imageView. clipsToBounds = true /* prevent image view size*/

将contentmodel设置为此

v.contentMode = .scaleAspectFit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM