Rotating image by 3*Double.pi/2 makes image not appear (swift3)

后端 未结 1 833
夕颜
夕颜 2021-01-07 14:51

Trying to rotate my image orientation by 270 degrees I can rotate by 90 degrees and the image appears however when rotating the image by 270 nothing happens. I have added 2

相关标签:
1条回答
  • 2021-01-07 15:04

    You can extend CIImage instead of UIImage and use core image filter CIAffineTransform using the transformation matrix. Start translating it to the center, rotate it 90 degrees (.pi/2) and move it back:

    extension CIImage {
        var image: UIImage? { return UIImage(ciImage: self) }
        func rotated(_ angle: CGFloat) -> CIImage? {
            let transform = CGAffineTransform(translationX: extent.midX, y: extent.midY)
                .rotated(by: angle * .pi /  180)
                .translatedBy(x: -extent.midX, y: -extent.midY)
            return CIFilter(name: "CIAffineTransform", withInputParameters: [kCIInputImageKey: self, kCIInputTransformKey: NSValue(cgAffineTransform: transform)])?.outputImage
        }
        var rotatedLeft: CIImage? { return rotated(90) }
        var rotatedRight: CIImage? { return rotated(-90) }
    }
    

    Playground testing:

    let image = UIImage(data: try! Data(contentsOf: URL(string:"https://i.stack.imgur.com/Xs4RX.jpg")!))!
    image.ciimage?.rotated(22.5)?.image
    image.ciimage?.rotatedRight?.image
    image.ciimage?.rotatedLeft?.image
    
    0 讨论(0)
提交回复
热议问题