Search code examples
iosios13

PKDrawing different results for Dark Mode and Light Mode


When using PKDrawing in dark mode the image generated by imageFromRect:scale: returns pen drawings in white color. In light mode it uses black color. The background is usually transparent.

Question: How can PKDrawing be forced to always behave like in light mode?


Solution

  • You can do it like this, by using traitCollection.performAsCurrent:

    let darkImage = thumbnail(drawing: drawing, thumbnailRect: frameForImage, traitCollection: UITraitCollection(userInterfaceStyle: .dark))
    
    func thumbnail(drawing: PKDrawing, thumbnailRect: CGRect, traitCollection: UITraitCollection) -> UIImage {
    
        var image = UIImage()
        traitCollection.performAsCurrent {
            image = drawing.image(from: thumbnailRect, scale: 2.0)
        }
        return image
    }