将文本放在drawRect中的其他CALayer之上

时间:2014-04-15 13:50:17

标签: ios objective-c calayer drawrect

我试图在CALayer上面显示文字,但不知怎的,我无法实现它。我使用了以下代码:

- (void)drawRect:(CGRect)rect
{
    self.layer.sublayers = nil;
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);

    // Code to show grid lines clipped

    CGRect overallRectForBarItem = CGRectMake(20, 20, 176, 35);
    CAShapeLayer *barItemShape = [CAShapeLayer layer];
    barItemShape.frame = overallRectForBarItem;
    barItemShape.path = [UIBezierPath bezierPathWithRect:overallRectForBarItem].CGPath;
    barItemShape.strokeColor = [UIColor lightGrayColor].CGColor;
    barItemShape.fillColor = [UIColor lightGrayColor].CGColor;
    [self.layer addSublayer:barItemShape];

    [self drawTextForBarItem:@"TESTING" inRect:CGRectMake(100, 40, 35, 0)];

    // Other code clipped

    CGContextRestoreGState(ctx);
}

-(void) drawTextForBarItem:(NSString*)barItemTitle inRect:(CGRect)rect
{
    float actualFontSize = 14.0;
    UIFont *font = [ISUtility getSystemFont:actualFontSize];
    CGSize size = [barItemTitle sizeWithFont:font];
    NSMutableParagraphStyle *paragraphStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentRight;
    [barItemTitle drawInRect:CGRectMake(rect.origin.x, rect.origin.y - size.height/2, rect.size.width, size.height) withAttributes:@{NSFontAttributeName:font, NSForegroundColorAttributeName:[UIColor blueColor], NSParagraphStyleAttributeName:paragraphStyle}];
}

以下是模拟器的屏幕截图。Screenshot

我也试过zPosition但没有用。

barItemShape.zPosition = -1000;

1 个答案:

答案 0 :(得分:1)

您遇到问题的最主要原因是您创建CGContextRef但在需要绘制浅灰色矩形时添加子图层。我认为,使用CoreGraphics函数绘制矩形并绘制文本会更加一致。

更详细一点,您似乎在当前图层中绘制文字,但添加了位于文本上方的子图层。

例如,您可以使用此代码试一试:

UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];

CGContextSetFillColorWithColor(context, redColor.CGColor);
CGContextFillRect(context, self.bounds);