2013-10-11 68 views
0

我在我看來有一個標籤。現在我想在標籤上方畫一條線,這意味着您可以看到標籤在該線之下。iOS在標籤上方畫一條線

到目前爲止,我可以使用quartz2D繪製一條線,但總是在標籤下。有什麼方法可以解決我的問題嗎?

+3

發佈您的代碼,以便我們可以爲您提供幫助。 – Lefteris

+0

你可以製作一個兩點高的UIView。 –

+0

當您說「在標籤下」時,是否意味着標籤遮住了線條(在這種情況下,如果您將標籤的背景顏色更改爲清晰)?或者你是說你畫的線的'y'座標是這樣的:它出現在標籤的底部而不是頂部。 – Rob

回答

1

說實話,最簡單的做法是創建一個名爲[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]; 
+0

爲什麼要使用圖片?只需將'lineView'的'backgroundColor'設置爲您需要的任何線條顏色,並使'lineView'高一點或兩點。 – rmaddy

+0

是的,這是一種解決方案。 – Bill

+0

@rmaddy使用圖像,您可以在Retina顯示屏上製作一條細小的1像素線,無需處理具有屏幕比例的額外條件。 –

3

您可以創建一個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]; 
0

如果這是您將使用大量的標籤,你可以創建一個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將在每一幀重新渲染。

對於獎勵積分,您可以使顏色和線寬屬性:)