iOS图片裁剪的一点感悟

最近在改的需求,需要裁剪图片,然后网上各种搜索,终于寻得一个仿微信头像裁剪的demo,改一改基本OK。但是第一次裁剪完的图片有些模糊,网上看帖子,有人提议把UIGraphicsBeginImageContext(size);这行代码改成如下形式:UIGraphicsBeginImageContextWithOptions(size,NO,kDeviceScale);这样的话,加了屏幕分辨率,缩放以后准备裁剪的图片确实不模糊了,但是诞生了一个新的问题,明明图片已经调整到裁剪框的中心也缩放到了想要的内容范围,但是裁剪以后的结果是只有图片右上角的1/4,好苦逼啊,然后又是各种尝试,各种问大神,最后又是分辨率的问题,擦,想死的节奏!记录一下给需要用到裁剪功能的同学提个醒,与及给正在为此问题烦恼的同学予希望之光。

- (UIImage *)getSubImage {
    
    CGRect squareFrame = self.cropFrame;
    
    CGFloat scaleRatio = self.latestFrame.size.width / self.originalImage.size.width;
    CGFloat x = (squareFrame.origin.x - self.latestFrame.origin.x) / scaleRatio;
    CGFloat y = (squareFrame.origin.y - self.latestFrame.origin.y) / scaleRatio;
    CGFloat w = squareFrame.size.width / scaleRatio;
    CGFloat h = squareFrame.size.width / scaleRatio;
    if (self.latestFrame.size.width < self.cropFrame.size.width) {
        CGFloat newW = self.originalImage.size.width;
        CGFloat newH = newW * (self.cropFrame.size.height / self.cropFrame.size.width);
        x = 0; y = y + (h - newH) / 2;
        w = newH; h = newH;
    }
    if (self.latestFrame.size.height < self.cropFrame.size.height) {
        CGFloat newH = self.originalImage.size.height;
        CGFloat newW = newH * (self.cropFrame.size.width / self.cropFrame.size.height);
        x = x + (w - newW) / 2; y = 0;
        w = newH; h = newH;
    }
    //乘以图片的分辨率,保证截到一张完整的图(分辨率:kDeviceScale)
    CGRect myImageRect = CGRectMake(x*kDeviceScale,y*kDeviceScale, w*kDeviceScale, h*kDeviceScale);
    CGImageRef imageRef = self.originalImage.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef, myImageRect);
    CGSize size;
    size.width = myImageRect.size.width;
    size.height = myImageRect.size.height;
    //UIGraphicsBeginImageContext(size);
    //设置图片的分辨率,保证图片的清晰度(kDeviceScale)
    UIGraphicsBeginImageContextWithOptions(size,NO,kDeviceScale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, myImageRect, subImageRef);
    UIImage *smallImage = [UIImage imageWithCGImage:subImageRef];
    CGImageRelease(subImageRef);
    UIGraphicsEndImageContext();
    return smallImage;
}

你可能感兴趣的:(iOS图片裁剪的一点感悟)