iOS 怎樣將網絡請求圖片與屏幕適配不變形

前兩天做項目,由于圖片的大小比例與給定imageView的大小比例不一致,導致圖片變形影響美觀;現做以下操作

//根據寬高剪切圖片

+(UIImage *)getImageFromUrl:(NSURL *)imgUrl imgViewWidth:(CGFloat)width imgViewHeight:(CGFloat)height;

#pragma mark-------根據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 轉image

UIImage * image ;

//根據網址將圖片轉化成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];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容