首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将文本放在drawRect中的其他drawRect上

将文本放在drawRect中的其他drawRect上
EN

Stack Overflow用户
提问于 2014-04-15 13:50:17
回答 1查看 508关注 0票数 2

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

代码语言:javascript
复制
- (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}];
}

下面是模拟器的屏幕截图。

我也尝试过zPosition,但没有用。

代码语言:javascript
复制
barItemShape.zPosition = -1000;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-15 14:42:17

造成问题的最可能原因是您创建了CGContextRef,但在需要绘制亮灰色矩形时添加了子层。我认为,用CoreGraphics函数绘制矩形和绘制文本会更加一致。

更详细的是,您似乎在当前层中绘制文本,但是添加了将在文本之上的子层。

例如,您可以使用这段代码来尝试:

代码语言:javascript
复制
UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0];

CGContextSetFillColorWithColor(context, redColor.CGColor);
CGContextFillRect(context, self.bounds);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23085712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档