func rotated()

in ios/SpectrumKit/SpectrumKitInstrumentationTestsHelpers/UIImage+Orientation.swift [18:54]


  func rotated(by degrees: Int) -> UIImage {
    guard degrees != 0 || self.imageOrientation != .up else {
      return self
    }

    guard let cgImage = self.cgImage else {
      fatalError("Failed to extract CGImage from UIImage")
    }

    let newSize = self.size.rotated(by: degrees)
    UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)

    defer {
      UIGraphicsEndImageContext()
    }

    guard let context = UIGraphicsGetCurrentContext() else {
      fatalError("Failed to get current image context")
    }

    context.translateBy(x: newSize.width / 2, y: newSize.height / 2)
    context.rotate(by: CGFloat(degrees + self.imageOrientation.degrees) * .pi / 180)

    context.scaleBy(x: self.imageOrientation.isMirrored.horizontally ? -1 : 1,
                    y: self.imageOrientation.isMirrored.vertically ? 1 : -1)

    let nonOrientationSpecificImageSize = self.size.rotated(by: -self.imageOrientation.degrees)
    context.draw(cgImage, in: CGRect(origin: CGPoint(x: -nonOrientationSpecificImageSize.width / 2,
                                                     y: -nonOrientationSpecificImageSize.height / 2),
                                     size: nonOrientationSpecificImageSize))

    guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
      fatalError("Failed to extract UIImage from context")
    }

    return image
  }