工作中突然用到了压缩图片展示缩略图被压扁和拉伸的现象,于是先按比例压缩然后再进行裁剪。类似UIView中的UIViewContentMode的UIViewContentModeScaleAspectFit效果
原图
UIViewContentModeScaleAspectFit
先将图片等比缩放再进行裁剪,下边是两种裁剪方法:
第一种方法
// CIImage实现
CIImage*ciimage = [CIImageimageWithCGImage:newImage.CGImage];
ciimage = [ciimageimageByCroppingToRect:cropRect];
CIContext*context = [CIContextcontext];
CGImageRefimageRef = [contextcreateCGImage:ciimagefromRect:cropRect];
newImage = [UIImageimageWithCGImage:imageRef];
第二种方法
// quartz 2d 实现
UIGraphicsBeginImageContext(cropRect.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGImageRefimageRef = newImage.CGImage;
CGImageRefsubImageRef =CGImageCreateWithImageInRect(imageRef, cropRect);
CGContextDrawImage(ctx, cropRect, subImageRef);
newImage = [UIImageimageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
第三种方法
// CGImage
newImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([newImage CGImage], cropRect)];