ios 图片裁剪

不改变原图片比例,对图片超出尺寸部分进行裁剪

- (void)viewDidLoad {
    
    [super viewDidLoad];
      
 UIImageView *hotImageView2 = [[UIImageView alloc] init];
    hotImageView2.frame        =CGRectMake(0, 50, 375, 100 );
    hotImageView2.image        = [self cutImage:[UIImage imageNamed:@"IMG_0739.JPG"] oringImageView:hotImageView2 ];
    [self.view addSubview:hotImageView2];
}
//裁剪图片  裁剪图片 裁剪图片
- (UIImage *)cutImage:(UIImage*)image oringImageView:(UIImageView *)imageView
{
    //压缩图片
    CGSize newSize;
    CGImageRef imageRef = nil;
    
    CGFloat height = imageView.frame.size.height;
    CGFloat width  = imageView.frame.size.width;
    
    CGFloat scale = (image.size.height / image.size.width) / (height / width);
//    || isnan(scale)
    if ((image.size.width / image.size.height) < (width / height)) {
        newSize.width  = image.size.width;
        newSize.height = image.size.width * height / width;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, fabs(image.size.height - newSize.height) / 2, newSize.width, newSize.height));
    } else {
        newSize.height = image.size.height;
        newSize.width = image.size.height * width / height;
        
        imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(fabs(image.size.width - newSize.width) / 2, 0, newSize.width, newSize.height));
    }
    return [UIImage imageWithCGImage:imageRef];
}

下图为原图,上图为按比例裁剪


裁剪对比.png

你可能感兴趣的:(ios 图片裁剪)