15

很抱歉这个问题,但我在 SO 中搜索了很多线程,但一无所获。

问题是:如何裁剪 UIImage 中的中心正方形?

我尝试了下面的代码,但没有成功。裁剪发生,但在左上角。

-(UIImage*)imageCrop:(UIImage*)original
{
    UIImage *ret = nil;

    // This calculates the crop area.

    float originalWidth  = original.size.width;
    float originalHeight = original.size.height;

    float edge = fminf(originalWidth, originalHeight);

    float posX = (originalWidth   - edge) / 2.0f;
    float posY = (originalHeight  - edge) / 2.0f;


    CGRect cropSquare = CGRectMake(posX, posY,
                                   edge, edge);


    // This performs the image cropping.

    CGImageRef imageRef = CGImageCreateWithImageInRect([original CGImage], cropSquare);

    ret = [UIImage imageWithCGImage:imageRef
                              scale:original.scale
                        orientation:original.imageOrientation];

    CGImageRelease(imageRef);

    return ret;
}
4

1 回答 1

16

添加更多信息,我在拍摄照片后使用此“裁剪”。

经过一些测试,我发现了一些有用的东西。

// If orientation indicates a change to portrait.
if(original.imageOrientation == UIImageOrientationLeft ||
   original.imageOrientation == UIImageOrientationRight)
{
    cropSquare = CGRectMake(posY, posX,
                            edge, edge);

}
else
{
    cropSquare = CGRectMake(posX, posY,
                            edge, edge);
}
于 2012-06-14T18:59:41.560 回答