简体   繁体   English

如何在UIImage中裁剪中心广场?

[英]How to crop a center square in a UIImage?

Sorry about this question, but I searched a lot of threads here in SO and I found nothing. 对这个问题感到抱歉,但我在SO搜索了很多帖子,但我一无所获。

The question is: how to crop a center square in a UIImage? 问题是:如何在UIImage中裁剪中心广场?

I tried the code bellow but without success. 我尝试了下面的代码,但没有成功。 The cropping happens, but in the upper-left corner. 裁剪发生,但在左上角。

-(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;
}

Adding more information, I'm using this 'crop' after a photo capture. 添加更多信息,我在拍照后使用这个“裁剪”。

After some tests, I found something that worked. 经过一些测试,我发现了一些有效的方法。

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM