Cropping center square of UIImage

后端 未结 18 661
日久生厌
日久生厌 2020-12-07 23:09

So here\'s where I\'ve made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn\'t transl

18条回答
  •  心在旅途
    2020-12-07 23:33

    This is an old question, but none of the answers are really correct (even the accepted answer). The important thing to understand is that UIImageOrientation (image.imageOrientation) is actually correct, but it's definition of UP and our definition of UP are different. For us, UP is the top of the device (where the power button is). For UIImageOrientation, UP is the side opposite of the volume control buttons. So if the device takes a picture with the volume controls down, this is UIImageOrientationUp. If you take a picture in portrait mode (with the home button down), this is UIImageOrientationLeft.

    So you can calculate the center in portrait, then you can apply the following transform to the image so that the crop is in the correct place.

    - (UIImage *)cropImage:(UIImage*)image toRect:(CGRect)rect {
        CGFloat (^rad)(CGFloat) = ^CGFloat(CGFloat deg) {
            return deg / 180.0f * (CGFloat) M_PI;
        };
    
        // determine the orientation of the image and apply a transformation to the crop rectangle to shift it to the correct position
        CGAffineTransform rectTransform;
        switch (image.imageOrientation) {
            case UIImageOrientationLeft:
                rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height);
                break;
            case UIImageOrientationRight:
                rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0);
                break;
            case UIImageOrientationDown:
                rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height);
                break;
            default:
                rectTransform = CGAffineTransformIdentity;
        };
    
        // adjust the transformation scale based on the image scale
        rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale);
    
        // apply the transformation to the rect to create a new, shifted rect
        CGRect transformedCropSquare = CGRectApplyAffineTransform(rect, rectTransform);
        // use the rect to crop the image
        CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, transformedCropSquare);
        // create a new UIImage and set the scale and orientation appropriately
        UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation];
        // memory cleanup
        CGImageRelease(imageRef);
    
        return result;
    }
    

    This code shifts the crop square so that it is in the correct relative position.

提交回复
热议问题