Cropping center square of UIImage

后端 未结 18 662
日久生厌
日久生厌 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:15

    improved from @Elmundo's answer

    +(UIImage *)getCenterMaxSquareImageByCroppingImage:(UIImage *)image withOrientation:(UIImageOrientation)imageOrientation
    
    {
        CGSize centerSquareSize;
        double oriImgWid = CGImageGetWidth(image.CGImage);
        double oriImgHgt = CGImageGetHeight(image.CGImage);
        NSLog(@"oriImgWid==[%.1f], oriImgHgt==[%.1f]", oriImgWid, oriImgHgt);
        if(oriImgHgt <= oriImgWid) {
            centerSquareSize.width = oriImgHgt;
            centerSquareSize.height = oriImgHgt;
        }else {
            centerSquareSize.width = oriImgWid;
            centerSquareSize.height = oriImgWid;
        }
    
        NSLog(@"squareWid==[%.1f], squareHgt==[%.1f]", centerSquareSize.width, centerSquareSize.height);
    
        double x = (oriImgWid - centerSquareSize.width) / 2.0;
        double y = (oriImgHgt - centerSquareSize.height) / 2.0;
        NSLog(@"x==[%.1f], x==[%.1f]", x, y);
    
        CGRect cropRect = CGRectMake(x, y, centerSquareSize.height, centerSquareSize.width);
        CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
    
        UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:imageOrientation];
        CGImageRelease(imageRef);
    
    
        return cropped;
    }
    

提交回复
热议问题