CALayer not displaying

2019-05-09 19:01发布

问题:

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

回答1:

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];
}


回答2:

You're adding a layer as a sublayer of itself. [self layer] returns the view's existing layer. If you want to create a separate layer, you have to do it manually. There's probably something in the view system that keeps circular references from iterating out of control.

As a point of reference, you should make it a habit of calling [super viewDidLoad] before you do anything else. And an easier way of creating a CGColor is to create a UIColor and get its CGColor property.