Generated Thumbnail won't set as UIButton Background Color

95 Views Asked by At

I recently came back to test a view controller which previously worked and took a locally saved video file, created a thumbnail from that file, and displayed the thumbnail as the background color of a UIButton using testButton.backgroundColor = UIColor(patternImage: image!) where image = generateThumbnail(). Now, for some reason, when I'm trying to cast the image as a pattern for the background color, the background color turns black, no image.

If I use an asset such as UIColor(patternImage: (UIImage(named: "Picture")) (instead of the UIImage generated from generateThumbnail()) the background color is set to the image, as expected.

Below is my generateThumbnail()

private func generateThumbnail(url: URL) -> UIImage? {

        let videoAsset : AVAsset = AVAsset(url: url)
        let assetImageGenerator : AVAssetImageGenerator = AVAssetImageGenerator(asset: videoAsset)
        assetImageGenerator.appliesPreferredTrackTransform = true

        var time = videoAsset.duration
        time.value = min(time.value, 2)

        do{
            let thumbnail = try assetImageGenerator.copyCGImage(at: time, actualTime: nil)
            let framedThumbnail : UIImage = UIImage(cgImage: thumbnail)
            return framedThumbnail
        } catch {
            print("Error saving thumbnail \(error.localizedDescription)")
            return nil
        }

    }

Here's an example of passing in UIImage to backgroundColor - which yields a black background


let urlTest = Bundle.main.url(forResource: "SampleVideo", withExtension: "mp4")!     
let image = generateThumbnail(url: urlTest)
let testButton = UIButton()
testButton.frame = CGRect(x: 0, y: 0, width: 400, height: 300)
testButton.backgroundColor = UIColor(patternImage: image!)

An example of loading local image from assets file - yields correctly, image set as background for button:

let image = UIImage(named: "Sample")
let testButton = UIButton()
testButton.frame = CGRect(x: 0, y: 0, width: 400, height: 300)
testButton.backgroundColor = UIColor(patternImage: image!)

And yes, the urlTest does generate an image when run through generateThumbnail. I can get it to display in a test UIImageView() as expected, not sure why it turns black when set as backgroundColor

tl;dr Why does my created thumbnail image not display as background for button when asset images will?

EDIT: Solved The Problem

Use the .setBackgroundImage method on UIButton. Solved example:

let urlTest = Bundle.main.url(forResource: "SampleVideo", withExtension: "mp4")!     
let image = generateThumbnail(url: urlTest)
let testButton = UIButton()
thumbButton.setBackgroundImage(image, for: .normal)

I don't recall seeing that method as an option on UIButton before, may be new in Swift 5 ¯\_(ツ)_/¯

0

There are 0 best solutions below