核心方法
CGImageCreateWithImageInRect(CGImageRef image, CGRect rect)
實(shí)現(xiàn)
UIImage *toCropImage = [image fixOrientation];
CGImageRef cgImage = CGImageCreateWithImageInRect(toCropImage.CGImage, croprect);
UIImage *cropped = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
return cropped;
這樣做會發(fā)現(xiàn),明明給了個正方形區(qū)域,但是寬高總有一邊多一個像素點(diǎn)。如果是裁剪大圖還好,要是裁剪一個10X10的正方形,裁出來11X10,就很明顯。
解決辦法:
查看官方API ( https://developer.apple.com/documentation/coregraphics/1454683-cgimagecreatewithimageinrect?language=objc)發(fā)現(xiàn),CGImageCreateWithImageInRect要傳 CGRectIntegral類型。
所以,區(qū)域需要都是整數(shù),如下處理一下就好了
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;
}