iOS 怎樣將網(wǎng)絡(luò)請(qǐng)求圖片與屏幕適配不變形

前兩天做項(xiàng)目,由于圖片的大小比例與給定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;

}

//對(duì)象方法

-(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];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容