我试图在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;
答案 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);