Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a UIImage from a CGImage in Swift?

Tags:

I'm trying to create a UIImage from the ALAssetsGroup#posterImage method. In Objective-C, I could simply call [UIImage imageWithCGImage:group.posterImage] but in Swift, UIImage(CGImage: group.posterImage) gives me a compiler error:

Could not find an overload for 'init' that accepts the supplied arguments 

What am I doing wrong?

like image 520
Bill Avatar asked Jun 20 '14 03:06

Bill


People also ask

How do you convert CIImage to UIImage?

This is most compatibile way of doing it: UIImage* u =[UIImage imageNamed:@"image. png"]; CIImage* ciimage = [[CIImage alloc] initWithCGImage:u. CGImage];

What is a UIImage?

An object that manages image data in your app.

What is CGImage in Swift?

A bitmap image or image mask.


1 Answers

If you look at the docs in Xcode6 you will see that posterImage() returns a Unmanaged<CGImage>! (in Swift, in ObjC it returns a CGImageRef). After some investigation from the docs I found this:

When you receive an unmanaged object from an unannotated API, you should immediately convert it to a memory managed object before you work with it.

So your solution would be:

UIImage(CGImage: group.posterImage().takeUnretainedValue()) 
like image 121
Firo Avatar answered Sep 23 '22 08:09

Firo