How do I mirror a UIImage picture from UIImagePickerController

后端 未结 6 1781
后悔当初
后悔当初 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条回答
  •  渐次进展
    2021-02-12 22:43

    You may think, why bother with the outrageously long switch statement?

    ? UIImage *flip = [UIImage imageWithCGImage:image.CGImage   
    ?                                     scale:image.scale
    ?                               orientation:(image.imageOrientation + 4) % 8];
    

    And if you take a look at the enum you can see that modular arithmetic would do:

    typedef NS_ENUM(NSInteger, UIImageOrientation) {
        UIImageOrientationUp,            // default orientation
        UIImageOrientationDown,          // 180 deg rotation
        UIImageOrientationLeft,          // 90 deg CCW
        UIImageOrientationRight,         // 90 deg CW
        UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
        UIImageOrientationDownMirrored,  // horizontal flip
        UIImageOrientationLeftMirrored,  // vertical flip
        UIImageOrientationRightMirrored, // vertical flip
    };
    

    But this code is too clever. You should write a function with an explicit switch statement instead. E.g.

    UIImageOrientation mirroredImageOrientation(UIImageOrientation orientation) {
        switch(orientation) {
            case UIImageOrientationUp: return UIImageOrientationUpMirrored;
            case UIImageOrientationDown: return UIImageOrientationDownMirrored;
            case UIImageOrientationLeft: return UIImageOrientationLeftMirrored;
            case UIImageOrientationRight: return UIImageOrientationRightMirrored;
            case UIImageOrientationUpMirrored: return UIImageOrientationUp;
            case UIImageOrientationDownMirrored: return UIImageOrientationDown;
            case UIImageOrientationLeftMirrored: return UIImageOrientationLeft;
            case UIImageOrientationRightMirrored: return UIImageOrientationRight;
            default: return orientation;
        }
    }
    

    And use the function like this:

    UIImage *flip = [UIImage imageWithCGImage:image.CGImage   
                                        scale:image.scale
                                  orientation:mirroredImageOrientation(image.imageOrientation)];
    

    I've added question marks to indicate questionable, smelly code. Similar to The Practice of Programming

提交回复
热议问题