How do I mirror a UIImage picture from UIImagePickerController

后端 未结 6 1775
后悔当初
后悔当初 2021-02-12 22:27

I\'m trying to figure out if there is any way to mirror an image. For example, take a picture of someone\'s face and then cut it in half and show what their face looks like with

6条回答
  •  猫巷女王i
    2021-02-12 22:54

    None of the answers above, respond to the part of question that is mirroring half of the image not flipping the whole image. Mixing the solutions leads to the following sample function you may use as a category such as UIImage+Mirroring :

    (UIImage *) horizontalMirror {
        UIImageOrientation flippedOrientation = UIImageOrientationUpMirrored;
        switch (self.imageOrientation) {
            case UIImageOrientationUp: break;
            case UIImageOrientationDown: flippedOrientation = UIImageOrientationDownMirrored; break;
        }
        UIImage * flippedImage = [UIImage imageWithCGImage:self.CGImage scale:1.0 orientation:flippedOrientation];
    
        CGImageRef inImage = self.CGImage;
        CGContextRef ctx = CGBitmapContextCreate(NULL,
                                                 CGImageGetWidth(inImage),
                                                 CGImageGetHeight(inImage),
                                                 CGImageGetBitsPerComponent(inImage),
                                                 CGImageGetBytesPerRow(inImage),
                                                 CGImageGetColorSpace(inImage),
                                                 CGImageGetBitmapInfo(inImage)
                                                 );
        CGRect cropRect = CGRectMake(flippedImage.size.width/2, 0, flippedImage.size.width/2, flippedImage.size.height);
        CGImageRef TheOtherHalf = CGImageCreateWithImageInRect(flippedImage.CGImage, cropRect);
        CGContextDrawImage(ctx, CGRectMake(0, 0, CGImageGetWidth(inImage), CGImageGetHeight(inImage)), inImage);
    
        CGAffineTransform transform = CGAffineTransformMakeTranslation(flippedImage.size.width, 0.0);
        transform = CGAffineTransformScale(transform, -1.0, 1.0);
        CGContextConcatCTM(ctx, transform);
    
        CGContextDrawImage(ctx, cropRect, TheOtherHalf);
    
        CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
        CGContextRelease(ctx);
        UIImage *finalImage = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
    
        return finalImage;
    }
    

提交回复
热议问题