How to stop an image from stretching within a UIIm

2020-02-17 04:30发布

I have a UIImageView where I have set the frame size to x = 0, y = 0, width = 404, height = 712. In my project, I need to change the image in UIImageView dynamically.

I am using this code to change the image:

self.imageView.image = [UIImage imageNamed:@"setting-image.png"];

The problem is, when the *.png image size is smaller than the UIImageView frame size, the image stretches. I don't want it to stretch. Is there any way to do that?

10条回答
2楼-- · 2020-02-17 05:00

Change the contentMode, e.g.:

imageView.contentMode = UIViewContentModeScaleAspectFit;
查看更多
该账号已被封号
3楼-- · 2020-02-17 05:02

How to use original size of image - without any stretching

  • Just change the UIImage's Mode from scale to fill to Aspect Fit within the interface builder.

enter image description here

查看更多
淡お忘
4楼-- · 2020-02-17 05:08

Change the UIImage's Mode from 'scale to fill' to 'Center' within the interface builder. Make sure your image is the exact size you need.

enter image description here

查看更多
时光不老,我们不散
5楼-- · 2020-02-17 05:10

still stretch when image is bigger than imageivew

swift

    let qCodeImage = UIImage(named: "qcode-placeholder.png")!      
    let qCodeImageView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(cardView.frame)-30, CGRectGetWidth(cardView.frame)-30))
    qCodeImageView.image = qCodeImage
    qCodeImageView.clipsToBounds = true
    qCodeImageView.contentMode = UIViewContentMode.ScaleToFill
    qCodeImageView.center = cardView.center
查看更多
Anthone
6楼-- · 2020-02-17 05:13

You can use

self.imageView.contentMode = UIViewContentModeScaleAspectFit;

Swift 3:

imageView.contentMode = .scaleAspectFit

Or UIViewContentModeCenter / .center, or any of the other modes described in the UIView documentation.

查看更多
成全新的幸福
7楼-- · 2020-02-17 05:13

Use the contentMode property. You probably want either UIViewContentModeScaleAspectFit or UIViewContentModeCenter.

查看更多
登录 后发表回答