简体   繁体   中英

Change UIImageView height to image height?

I have a UIImageView set up which will display an image determined by what the user selected in the previous table view.

This is how I am currently displaying my images:

if ([_TitleLabel.text isEqualToString:@"Dog"]) {
    UIImage *image = [UIImage imageNamed:@"Dog.png"];
    [imageView setImage:image];
}

Subsequent if statements follow displaying the different images for a different animal.

These images need to be of a different height, and I need to keep their proportionality. The width of all the images is 320 pts. The heights vary from anywhere between 1000pts to 2500pts. All images are located locally in the project. I want the height of the UIImageView to change to the height of image which corresponds to the animal selected by the user. Any ideas?

You can update the imageView's frame width and height using UIImage's width and height, like this:

if ([_TitleLabel.text isEqualToString:@"Dog"]) {
    UIImage *image = [UIImage imageNamed:@"Dog.png"];
    [imageView setImage:image];

    // update image view frame width and height.
    imageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, image.size.width, image.size.height);
}

Note:

Using UIViewContentModeScaleAspectFit will leave space between your image and the UIImageView boundary if the image is different aspect ratio to your UIImageView frame, which isn't likely what you want.

Nor will UIViewContentModeScaleAspectFill help, your image will become truncated within the frame of your imageView.

imageView.contentMode = UIViewContentModeCenter;
if (imageView.bounds.size.width > ((UIImage*)imagesArray[i]).size.width && imageView.bounds.size.height > ((UIImage*)imagesArray[i]).size.height) {
       imageView.contentMode = UIViewContentModeScaleAspectFit;
}

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