我试图在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}];
}下面是模拟器的屏幕截图。

我也尝试过zPosition,但没有用。
barItemShape.zPosition = -1000;发布于 2014-04-15 14:42:17
造成问题的最可能原因是您创建了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);https://stackoverflow.com/questions/23085712
复制相似问题