不改變原圖片比例护昧,對圖片超出尺寸部分進(jìn)行裁剪
- (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];
}
下圖為原圖侮腹,上圖為按比例裁剪