2017-04-03 100 views
0

我已經生成了一個包含CAShapeLayer的圓圈,現在正試圖通過CATextLayer在其上添加一個標籤,但它並未顯示出來。我不知道我錯過了什麼?在CAShapeLayer上添加文本

CAShapeLayer *circleLayer = [CAShapeLayer layer]; 
[circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(carouselView.frame.size.width - 42, addCardButton.frame.origin.y - 5, 20, 20)] CGPath]]; 
[circleLayer setStrokeColor:[[UIColor whiteColor] CGColor]]; 
[circleLayer setFillColor:[[UIColor redColor] CGColor]]; 

CATextLayer* text = [CATextLayer new]; 
text.string = @"1"; 
text.fontSize = 25; 
text.frame = CGRectMake(0,0,60,60); 
text.position = CGPointMake(CGRectGetMidX(circleLayer.frame) ,CGRectGetMidY(circleLayer.frame)); 
CGFloat vert = CGRectGetMidY(circleLayer.frame)/CGRectGetHeight(text.frame); 
text.anchorPoint = CGPointMake(0.5, vert); 
text.alignmentMode = kCAAlignmentCenter; 
text.foregroundColor = [[UIColor blackColor] CGColor]; 

[circleLayer addSublayer:text]; 
[[carouselView layer] addSublayer:circleLayer]; 

回答

0

實際上沒有什麼缺失,唯一的問題是圖層的框架。當您設置圓形圖層時,您不提供框架,並且bezierPathWithOvalInRect:不會執行此操作。所以它的框架仍然是(0.0, 0.0, 0.0, 0.0),這意味着文本層也位於(0.0, 0.0)(因爲您將其框架設置爲(0,0,60,60))。因此,文本圖層位於屏幕的左上角,您可能無法觀察它,因爲它被其他東西所覆蓋(我不知道您的視圖層次結構如何)。正確設置圓形圖層的框架可以解決問題。