Crop image to a square according to the size of a UIView/CGRect

前端 未结 3 1694
栀梦
栀梦 2021-02-20 13:42

I have an implementation of AVCaptureSession and my goal is for the user to take a photo and only save the part of the image within the red square border, as shown below:

<
相关标签:
3条回答
  • 2021-02-20 14:20

    You can crop images with CGImageCreateWithImageInRect:

    CGImageRef imageRef = CGImageCreateWithImageInRect([uncroppedImage CGImage], bounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    0 讨论(0)
  • 2021-02-20 14:20

    Swift 3:

    let imageRef:CGImage = uncroppedImage.cgImage!.cropping(to: bounds)!
    let croppedImage:UIImage = UIImage(cgImage: imageRef)
    
    0 讨论(0)
  • 2021-02-20 14:24

    Don't forget to add scale parameter otherwise you will get low resolution image

    CGImageRef imageRef = CGImageCreateWithImageInRect([uncroppedImage CGImage], CGRectMake(0, 0, 30, 120));
    [imageView setImage:[UIImage imageWithCGImage:imageRef scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp]];
    CGImageRelease(imageRef);
    
    0 讨论(0)
提交回复
热议问题