如何在iOS中裁剪大图像的中心部分?

当从中心裁剪图像时,裁剪图像将采用源图像的纵横比,但根据我的要求,纵横比将随新裁剪尺寸而变化.

我希望获得具有新纵横比的图像的精确中心部分.例如,大图像的大小(320 * 480)然后我想裁剪尺寸(100,100)的图像的中心部分,纵横比也将是100 * 100 ,不需要外部白色或黑色部分,图像质量也很高.

裁剪功能:

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

    //Note : rec is nothing but the image frame which u want to crop exactly.

    rect = CGRectMake(rect.origin.x*image.scale,
                      rect.origin.y*image.scale,
                      rect.size.width*image.scale,
                      rect.size.height*image.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef
                                          scale:image.scale
                                    orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

请帮我.

最佳答案
这可能会运行

- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    // not equivalent to image.size (which depends on the imageOrientation)!
    double refWidth = CGImageGetWidth(image.CGImage);
    double refHeight = CGImageGetHeight(image.CGImage);

    double x = (refWidth - size.width) / 2.0;
    double y = (refHeight - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:self.imageOrientation];
    CGImageRelease(imageRef);

    return cropped;
}

转载注明原文:如何在iOS中裁剪大图像的中心部分? - 代码日志