iOS 精确的图片裁剪

核心方法

    CGImageCreateWithImageInRect(CGImageRef image, CGRect rect)

实现

    UIImage *toCropImage = [image fixOrientation];

    CGImageRef cgImage = CGImageCreateWithImageInRect(toCropImage.CGImage, croprect);

    UIImage *cropped = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

     return cropped;

这样做会发现,明明给了个正方形区域,但是宽高总有一边多一个像素点。如果是裁剪大图还好,要是裁剪一个10X10的正方形,裁出来11X10,就很明显。

解决办法:

查看官方API ( https://developer.apple.com/documentation/coregraphics/1454683-cgimagecreatewithimageinrect?language=objc)发现,CGImageCreateWithImageInRect要传 CGRectIntegral类型。

所以,区域需要都是整数,如下处理一下就好了

CGRect croprect = CGRectMake(floor(x), floor(y), round(width), round(height));

贴上完整方法

- (UIImage *)cropImage:(UIImage *)image toRect:(CGRect)rect {

    CGFloat x = rect.origin.x;

    CGFloat y = rect.origin.y;

    CGFloat width = rect.size.width;

    CGFloat height = rect.size.height;

    CGRect croprect = CGRectMake(floor(x), floor(y), round(width), round(height));

    UIImage *toCropImage = [image fixOrientation];// 纠正方向

    CGImageRef cgImage = CGImageCreateWithImageInRect(toCropImage.CGImage, croprect);

    UIImage *cropped = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    return cropped;

}

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

推荐阅读更多精彩内容