Resize UIImage and change the size of UIImageView

后端 未结 7 991
梦谈多话
梦谈多话 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 04:56
       if([[SDWebImageManager sharedManager] diskImageExistsForURL:[NSURL URLWithString:@"URL STRING1"]])
       {
           NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:@"URL STRING1"]];
    
           UIImage *tempImage=[self imageWithImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key] scaledToWidth:cell.imgview.bounds.size.width];
           cell.imgview.image=tempImage;
    
       }
       else
       {
           [cell.imgview sd_setImageWithURL:[NSURL URLWithString:@"URL STRING1"] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
            {
                UIImage *tempImage=[self imageWithImage:image scaledToWidth:cell.imgview.bounds.size.width];
                cell.imgview.image=tempImage;
    //                [tableView beginUpdates];
    //                [tableView endUpdates];
    
            }];
       }
    
    0 讨论(0)
  • 2020-12-13 04:58

    When you get the width and height of a resized image Get width of a resized image after UIViewContentModeScaleAspectFit, you can resize your imageView:

    imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight);
    imageView.center = imageView.superview.center;
    

    I haven't checked if it works, but I think all should be OK

    0 讨论(0)
  • 2020-12-13 05:02

    Use the category below and then apply border from Quartz into your image:

    [yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    [yourimage.layer setBorderWidth:2];
    

    The category: UIImage+AutoScaleResize.h

    #import <Foundation/Foundation.h>
    
    @interface UIImage (AutoScaleResize)
    
    - (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;
    
    @end
    

    UIImage+AutoScaleResize.m

    #import "UIImage+AutoScaleResize.h"
    
    @implementation UIImage (AutoScaleResize)
    
    - (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
    {
        UIImage *sourceImage = self;
        UIImage *newImage = nil;
        CGSize imageSize = sourceImage.size;
        CGFloat width = imageSize.width;
        CGFloat height = imageSize.height;
        CGFloat targetWidth = targetSize.width;
        CGFloat targetHeight = targetSize.height;
        CGFloat scaleFactor = 0.0;
        CGFloat scaledWidth = targetWidth;
        CGFloat scaledHeight = targetHeight;
        CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
        if (CGSizeEqualToSize(imageSize, targetSize) == NO)
        {
            CGFloat widthFactor = targetWidth / width;
            CGFloat heightFactor = targetHeight / height;
    
            if (widthFactor > heightFactor)
            {
                scaleFactor = widthFactor; // scale to fit height
            }
            else
            {
                scaleFactor = heightFactor; // scale to fit width
            }
    
            scaledWidth  = width * scaleFactor;
            scaledHeight = height * scaleFactor;
    
            // center the image
            if (widthFactor > heightFactor)
            {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            }
            else
            {
                if (widthFactor < heightFactor)
                {
                    thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
                }
            }
        }
    
        UIGraphicsBeginImageContext(targetSize); // this will crop
    
        CGRect thumbnailRect = CGRectZero;
        thumbnailRect.origin = thumbnailPoint;
        thumbnailRect.size.width  = scaledWidth;
        thumbnailRect.size.height = scaledHeight;
    
        [sourceImage drawInRect:thumbnailRect];
    
        newImage = UIGraphicsGetImageFromCurrentImageContext();
    
        if(newImage == nil)
        {
            NSLog(@"could not scale image");
        }
    
        //pop the context to get back to the default
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-13 05:06

    This is the Swift equivalent for Rajneesh071's answer, using extensions

    UIImage {
      func scaleToSize(aSize :CGSize) -> UIImage {
        if (CGSizeEqualToSize(self.size, aSize)) {
          return self
        }
    
        UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0)
        self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
      }
    }
    

    Usage:

    let image = UIImage(named: "Icon")
    item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 05:21

    I think what you want is a different content mode. Try using UIViewContentModeScaleToFill. This will scale the content to fit the size of ur UIImageView by changing the aspect ratio of the content if necessary.

    Have a look to the content mode section on the official doc to get a better idea of the different content mode available (it is illustrated with images).

    0 讨论(0)
提交回复
热议问题