Resize UIImage and change the size of UIImageView

后端 未结 7 1032
梦谈多话
梦谈多话 2020-12-13 04:37

I have this UIImageView and I have the values of its max height and max width. What I want to achieve is that I want to take the image (with any aspect ratio an

7条回答
  •  心在旅途
    2020-12-13 05:17

    If you have the size of the image, why don't you set the frame.size of the image view to be of this size?

    EDIT----

    Ok, so seeing your comment I propose this:

    UIImageView *imageView;
    //so let's say you're image view size is set to the maximum size you want
    
    CGFloat maxWidth = imageView.frame.size.width;
    CGFloat maxHeight = imageView.frame.size.height;
    
    CGFloat viewRatio = maxWidth / maxHeight;
    CGFloat imageRatio = image.size.height / image.size.width;
    
    if (imageRatio > viewRatio) {
        CGFloat imageViewHeight = round(maxWidth * imageRatio);
        imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
    }
    else if (imageRatio < viewRatio) {
        CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
        imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
    } else {
        //your image view is already at the good size
    }
    

    This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.

    PS: I hope you're setting imageView.layer.shouldRasterise = YES and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

    if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.

提交回复
热议问题