核心方法
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;
}