//
//  ZZHImageExtension.swift
//  SwiftProject
//
//  Created by aaa on 2024/3/15.
//

import Foundation
import UIKit

extension UIImage {
    func rotate(radians: CGFloat) -> UIImage {
        let rotatedSize = CGRect(origin: .zero, size: size)
            .applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
            .integral.size
        UIGraphicsBeginImageContext(rotatedSize)
        if let context = UIGraphicsGetCurrentContext() {
            let origin = CGPoint(x: rotatedSize.width / 2.0,
                                 y: rotatedSize.height / 2.0)
            context.translateBy(x: origin.x, y: origin.y)
            context.rotate(by: radians)
            draw(in: CGRect(x: -origin.y, y: -origin.x,
                            width: size.width, height: size.height))
            let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return rotatedImage ?? self
        }

        return self
    }
    
    //返回正向图片
    func getUpImg()->UIImage {
        let dg = getRotateFrom()
        let rotatedImage = rotate(radians:dg)
        return rotatedImage
    }
    
    func getRotateFrom() ->CGFloat {
        print("..or:\(self.imageOrientation)")
        if self.imageOrientation == .left {
            return .pi/2
        } else if self.imageOrientation == .right{
            return -.pi/2
        }
        else {
            return -.pi/2
        }
    }
}

