简体   繁体   English

Swift scaleAspect仅填充宽度

[英]Swift scaleAspectFill only width

I have got a UIImageView in Swift 我在Swift中有一个UIImageView

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. 我要做的是获取此图像的100x100像素 ,并仅显示该像素。 Just like in this image. 就像这张图片一样。

You have to set two properties of UIImageView. 您必须设置UIImageView的两个属性。

Programmatically: 以编程方式:

imgView.contentMode = .center
imgView.clipsToBounds = true

If you are using Storyboard, then you can set directly: 如果您使用的是Storyboard,则可以直接设置:

在此处输入图片说明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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