iOS 图片缩放

  • 按指定尺寸缩放图片
/**
 按指定尺寸缩放图片

 @param image 原始图片
 @param size  缩放尺寸
 @return      缩放后的图片
 */
+ (UIImage *)originImage:(UIImage *)image scaleToSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [image drawInRect:CGRectMake(0.f, 0.f, size.width, size.height)];
    UIImage *scaleImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaleImage;
}
  • 根据屏幕的宽高等比压缩图片
/**
 根据屏幕的宽高等比压缩图片

 @param originImage 原始图片
 @return 缩放后的图片
 */
+ (UIImage *)compressImage:(UIImage *)originImage {
    CGSize size = originImage.size;
    CGFloat scale = 1.f;
    
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    
    if (size.width > screenSize.width || size.height > screenSize.height) {
        if (size.width > size.height) {
            scale = screenSize.width / size.width;
        } else {
            scale = screenSize.height / size.height;
        }
    }
    
    CGSize scaleSize = CGSizeMake(size.width * scale, size.height * scale);
    
    UIGraphicsBeginImageContext(screenSize);
    [originImage drawInRect:CGRectMake(0.f, 0.f, scaleSize.width, scaleSize.height)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

你可能感兴趣的:(iOS 图片缩放)