我在我看來有一個標籤。現在我想在標籤上方畫一條線,這意味着您可以看到標籤在該線之下。iOS在標籤上方畫一條線
到目前爲止,我可以使用quartz2D繪製一條線,但總是在標籤下。有什麼方法可以解決我的問題嗎?
我在我看來有一個標籤。現在我想在標籤上方畫一條線,這意味着您可以看到標籤在該線之下。iOS在標籤上方畫一條線
到目前爲止,我可以使用quartz2D繪製一條線,但總是在標籤下。有什麼方法可以解決我的問題嗎?
說實話,最簡單的做法是創建一個名爲[email protected]的2x2像素圖像,並且底部2像素爲黑色,頂部2爲透明,然後將其用作圖像的背景圖像視圖。通過將圖像視圖用作圖案圖像,將圖像視圖拉伸到任何需要的寬度。 1x圖像應該是1x1px,全黑。
UIView *lineView = [[UIView alloc] initWithFrame:frame]; // Whatever frame the line needs
// Add the line image as a pattern
UIColor *patternColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"line.png"]];
lineView.backgroundColor = patternColor;
[self.view addSubview:lineView];
您可以創建一個CAShapeLayer
這樣的:
CAShapeLayer *lineLayer = [CAShapeLayer layer];
lineLayer.frame = self.label.bounds;
lineLayer.strokeColor = [UIColor redColor].CGColor;
CGRect rect = CGRectMake(0, CGRectGetMidY(lineLayer.bounds), lineLayer.bounds.size.width, 2);
lineLayer.path = [UIBezierPath bezierPathWithRect:rect].CGPath;
然後將其添加到UILabel
這樣的:
[self.label.layer addSublayer:lineLayer];
如果這是您將使用大量的標籤,你可以創建一個UILabel的子類並覆蓋drawRect函數。
- (void) drawRect:(CGRect)r
{
[super drawRect:r];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, 1.0, 1.0);
CGContextAddLineToPoint(context, self.bounds.size.width - 1.0, 1.0);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
這裏的優點是,該行將「烘烤」到視圖中,只能繪製一次。其他方法如CAShapeLayer或UIView將在每一幀重新渲染。
對於獎勵積分,您可以使顏色和線寬屬性:)
發佈您的代碼,以便我們可以爲您提供幫助。 – Lefteris
你可以製作一個兩點高的UIView。 –
當您說「在標籤下」時,是否意味着標籤遮住了線條(在這種情況下,如果您將標籤的背景顏色更改爲清晰)?或者你是說你畫的線的'y'座標是這樣的:它出現在標籤的底部而不是頂部。 – Rob