iOS裁剪图片

工作中突然用到了压缩图片展示缩略图被压扁和拉伸的现象,于是先按比例压缩然后再进行裁剪。类似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)];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容