How do I set the contents of a CALayer to a CGImageRef?
Asked Answered
R

2

10

I want to set the contents of a CALayer to an image. The CALayer has a contents property The documentation on that property says that "a layer can set this property to a CGImageRef to display the image as its contents." But the property takes an id so in Xcode I get the following issue:

Semantic Issue: Incompatible pointer types assigning to 'id' from 'CGImageRef' (aka 'struct CGImage *')

How can I assign a CGImageRef to the contents property when it only takes an id? What am I missing here?

Rockaway answered 28/3, 2011 at 5:35 Comment(0)
S
6

Explicitly casting CGImageRef to id should fix the warning. For example,

CGImageRef imageRef;

...

layer.contents = (id) imageRef;

should be working fine.

Stealthy answered 28/3, 2011 at 5:46 Comment(2)
Bingo. I don't entirely understand why though. CGImageRef isn't an NSObject and therefore can't be represented as an id... right? What's actually happening in this cast?Rockaway
@SimonCave Casting to id cost nothing at runtime. Actually, the compiled binary should even look the same with or without casting. The point is that the document told us we can set CGImageRef to contents, so we just blindly believe it. The internal implementation might actually just cast it back to CGImageRef if it's the only valid type for the contents according to the documentation.Stealthy
T
11

Instead of using (id) you can use (__bridge id) to solve the type convert issue.

Te answered 6/3, 2012 at 14:43 Comment(1)
+1 jerry. i found that a simple (id) cast did not work but your suggestion did. is it because i'm using c++11?Mariannmarianna
S
6

Explicitly casting CGImageRef to id should fix the warning. For example,

CGImageRef imageRef;

...

layer.contents = (id) imageRef;

should be working fine.

Stealthy answered 28/3, 2011 at 5:46 Comment(2)
Bingo. I don't entirely understand why though. CGImageRef isn't an NSObject and therefore can't be represented as an id... right? What's actually happening in this cast?Rockaway
@SimonCave Casting to id cost nothing at runtime. Actually, the compiled binary should even look the same with or without casting. The point is that the document told us we can set CGImageRef to contents, so we just blindly believe it. The internal implementation might actually just cast it back to CGImageRef if it's the only valid type for the contents according to the documentation.Stealthy

© 2022 - 2024 — McMap. All rights reserved.