前兩天做項目哨查,由于圖片的大小比例與給定imageView的大小比例不一致契邀,導(dǎo)致圖片變形影響美觀当纱;現(xiàn)做以下操作
//根據(jù)寬高剪切圖片
+(UIImage *)getImageFromUrl:(NSURL *)imgUrl imgViewWidth:(CGFloat)width imgViewHeight:(CGFloat)height;
#pragma mark-------根據(jù)imgView的寬高獲得圖片的比例
+(UIImage *)getImageFromUrl:(NSURL *)imgUrl imgViewWidth:(CGFloat)width imgViewHeight:(CGFloat)height{
UIImage * image =[[UIImage alloc] init];
UIImage * newImage =? [image getImageFromUrl:imgUrl imgViewWidth:width imgViewHeight:height];
return newImage;
}
//對象方法
-(UIImage *)getImageFromUrl:(NSURL *)imgUrl imgViewWidth:(CGFloat)width imgViewHeight:(CGFloat)height{
//data 轉(zhuǎn)image
UIImage * image ;
//根據(jù)網(wǎng)址將圖片轉(zhuǎn)化成image
NSData * data = [NSData dataWithContentsOfURL:imgUrl];
image =[UIImage imageWithData:data];
//圖片剪切
UIImage * newImage = [self cutImage:image imgViewWidth:width imgViewHeight:height];
return newImage;
}
//裁剪圖片
- (UIImage *)cutImage:(UIImage*)image imgViewWidth:(CGFloat)width imgViewHeight:(CGFloat)height
{
//壓縮圖片
CGSize newSize;
CGImageRef imageRef = nil;
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];
}