R
R
Rustem Saifullin2020-11-25 00:05:56
Swift
Rustem Saifullin, 2020-11-25 00:05:56

Why appears in the work with UIGraphics?

Good afternoon, I use this code to rotate images by a certain degree:

func rotated(degrees: CGFloat) -> UIImage? {
       let degreesToRadians: (CGFloat) -> CGFloat = { (degrees: CGFloat) in
         return degrees / 180.0 * CGFloat.pi
       }
       // Calculate the size of the rotated view's containing box for our drawing space
       let rotatedViewBox: UIView = UIView(frame: CGRect(origin: .zero, size: size))
       rotatedViewBox.transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
       let rotatedSize: CGSize = rotatedViewBox.frame.size

       // Create the bitmap context
       UIGraphicsBeginImageContextWithOptions(rotatedSize, false, 0.0)

       guard let bitmap: CGContext = UIGraphicsGetCurrentContext(), let unwrappedCgImage: CGImage = cgImage else {
        fatalError("не фортануло1")
       }

       // Move the origin to the middle of the image so we will rotate and scale around the center.
       bitmap.translateBy(x: rotatedSize.width/2.0, y: rotatedSize.height/2.0)

       // Rotate the image context
       bitmap.rotate(by: degreesToRadians(degrees))

       bitmap.scaleBy(x: CGFloat(1.0), y: -1.0)

       let rect: CGRect = CGRect(
           x: -size.width/2,
           y: -size.height/2,
           width: size.width,
           height: size.height)

       bitmap.draw(unwrappedCgImage, in: rect)

      let newImage = UIGraphicsGetImageFromCurrentImageContext()!

       UIGraphicsEndImageContext()
            return newImage
       
     }


And sometimes there is an error in this line
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
as if UIGraphicsGetImageFromCurrentImageContext = nil. But this does not always happen, if I restart the program, then everything is ok. Tell me, what could be the reasons? Can problems with streams?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question