gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:56 26 4
gpt4 key购买 nike

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

最佳答案

问题的最可能原因是您创建了 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);

关于ios - 在 drawRect 中将文本放在其他 CALayer 之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23085712/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com