iOS 精確的圖片裁剪

核心方法

    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;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容