So this is my first ever attempt at using a CALayer. Build is successful and no reported bugs, so I assume I must be doing something obviously wrong. But the layer does not display at all.
- (void)viewDidLoad
{
// Get Reliant Magenta in amazingly verbose manner
CGColorSpaceRef rgbaColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat reliantMagentaValues[4] = {(208/255),(27/255),(124/255),0.3f};
CGColorRef reliantMagenta = CGColorCreate(rgbaColorSpace, reliantMagentaValues);
CALayer *reliantCanvasLayer = [CALayer layer];
reliantCanvasLayer.backgroundColor = reliantMagenta;
reliantCanvasLayer.frame = CGRectMake(0, 0, 640, 960);
[super viewDidLoad];
[[[self view] layer] addSublayer:reliantCanvasLayer];
CGColorRelease(reliantMagenta);
}
Instead of a full page of magenta, I get back an empty view of grey. How am I messing up something this simple?
UPDATE
- (void)viewDidLoad
{
[super viewDidLoad];
// Get Reliant Magenta in amazingly verbose manner
CGColorSpaceRef rgbaColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat reliantMagentaValues[4] = {(208/255),(27/255),(124/255),0.3f};
CGColorRef reliantMagenta = CGColorCreate(rgbaColorSpace, reliantMagentaValues);
[[self view] layer].backgroundColor = reliantMagenta;
CGColorRelease(reliantMagenta);
}
same problem, but view is now black and not displaying elements added in the storyboard
One problem (possibly the only problem) is that you're creating your color with all zero components. When you say 208/255
, the compiler performs the division using integers and drops the remainder, so 208/255
is 0. You need to divide in floating point: 208.0f / 255.0f
.
It's also much easier to use a UIColor
instead of setting up the CGColorSpace
and the CGColor
yourself. Try this:
- (void)viewDidLoad {
[super viewDidLoad];
UIColor *reliantMagenta = [UIColor colorWithRed:208.0f / 255.0f
green:27.0f / 255.0f blue:124.0f / 255.0f alpha:0.3f];
CALayer *magentaLayer = [CALayer layer];
magentaLayer.frame = CGRectMake(0, 0, 640, 960);
magentaLayer.backgroundColor = reliantMagenta.CGColor;
[self.view.layer addSublayer:magentaLayer];
}