Yuto
Yuto

Reputation: 678

Converting PKDrawing to Image fails when dark mode is enabled

I am trying to convert PKDrawing to UIImage and save them to photos. This works correctly when dark mode is turned off, but when it's on, since the background color is white when saving as an image, the white lines disappear.

Summary of below : self.traitCollection.performAsCurrent doesn't fix the problem

Here are the codes I have tried using the references below (result images are below)

1

self.traitCollection.performAsCurrent {
var image:UIImage!
self.view.traitCollection.performAsCurrent {
    let drawing = note.drawing as? PKDrawing
    image = drawing!.image(from: drawing!.bounds, scale: 1.0)
}

let action = UIActivityViewController(activityItems: [image!],
                                      applicationActivities: nil)
action.popoverPresentationController?.sourceView = self.collectionView.cellForItem(at: indexPath)
self.present(action, animated: true, completion:nil)
}

2

self.traitCollection.performAsCurrent {
            var image:UIImage!
            var drawing:PKDrawing!
            drawing = note.drawing as? PKDrawing
            image = drawing.image(from: drawing.bounds, scale: 1.0)
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
        }

The first image is from when dark mode is off and the second one is when it's on

Dark Mode Off Image Dark Mode Image

Reference 1 Reference 2

Upvotes: 1

Views: 649

Answers (1)

Yuto
Yuto

Reputation: 678

This is not the perfect answer but for my situation, I solved it by forcing dark mode off in the code

var image:UIImage!
let userInterfaceStyle = self.traitCollection.userInterfaceStyle                   
self.overrideUserInterfaceStyle = .light
let drawing = note.drawing as? PKDrawing
self.overrideUserInterfaceStyle = .unspecified

hope this helps

Upvotes: 1

Related Questions