3

In my view's initWithFrame I create a root layer, and then add a sublayer to it. I set the sublayer's path so it will draw a colored box. I want to have text appear on top of the box, so in my view's drawRect, I use NSString's drawInRect method to render the text, but it is always drawn behind the box.

Is there any way to change the depth to somehow draw the text in front of the colored box layer?

picture: http://i.imgur.com/zins6.png

with low opacity on the sublayer: http://i.imgur.com/qyJLU.png

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self)
    {
        rootLayer = [CALayer layer];
        rootLayer.frame = self.frame;
        [self.layer addSublayer:rootLayer];

        sublayerPath = CGPathCreateMutable();
        CGPathAddRect(sublayerPath, nil, sublayerRect);
        CGPathCloseSubpath(sublayerPath);

        sublayer = [CAShapeLayer layer];
        sublayer.path = sublayerPath;
        sublayer.fillColor = [[UIColor greenColor] CGColor];
        sublayer.strokeColor = [[UIColor blackColor] CGColor];
        [rootLayer addSublayer:sublayer];

        ...
    }
    return self;
}


- (void)drawRect:(CGRect)rect
{

    ...

    [myString drawInRect:sublayerRect withFont:[UIFont fontWithName:@"Helvetica-Bold" size:21] lineBreakMode:UILineBreakModeTailTruncation alignment:UITextAlignmentCenter];    
}

I've already tried adding a CATextLayer to the sublayer instead - it works, but is slower (each of the views are in a UITableViewCell, and it scrolls much smoother using the NSString drawInRect method).

So does anyone know a way I can draw the string on top of the sublayer? I've tried setting the sublayer's z-position lower with no effect. I'm not sure how to change the depth of the drawRect graphics context, or if it's possible.

ryleigh
  • 218
  • 2
  • 11
  • To be honest, I don't even remember what was going through my head when I asked this. As far as I understand it now, since the layer is on top of the view, text drawn to the view's context will always show behind the layer - so either draw what you need in the drawRect (before drawing the text) instead of using a sublayer, or I think you can use some delegate methods to draw the text inside the sublayer yourself: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreAnimation_guide/Articles/ProvidingCALayerContent.html – ryleigh Dec 04 '11 at 19:52
  • I got the same issue when drawing a line.. hope someone has a solution – Van Du Tran Apr 17 '14 at 18:25

0 Answers0