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

}

你可能感兴趣的:(iOS 怎样将网络请求图片与屏幕适配不变形)