2012-01-27 49 views
4

我知道,在iOS版3.0+我可以使用我該如何只圍繞UILabel的頂部兩個角?

label.layer.cornerRadius = xxx; 

圓一個UILabel的所有四個角(作爲UIView子類),但我想圓只有標籤的上面兩個角,並保持底角直角。

有什麼辦法可以用UILabel做到這一點?其他解決方案假設一個自定義的UIView,而不是一個UILabel。

回答

16

你可以做到這一點使用CALayers和口罩

CAShapeLayer *maskLayer = [CAShapeLayer layer]; 
maskLayer.path = maskPath.CGPath; 
label.layer.mask = maskLayer; 

其中maskPath是使用bezierPathWithRoundedRect:byRoundingCorners:cornerRadii

+0

很酷,學到了一種新方法... – 2012-01-27 14:22:37

+0

我認爲它應該是label.layer.mask = maskLayer – Anand 2012-01-28 09:45:58

+0

@Anand正確,編輯 – wattson12 2012-01-28 12:24:02

1

我檢查了UIView的類參考& UILabel及其圖層,但找不到用iOS提供的方法做到這一點的方法。

你可以做一件事,創建一個UIView &對它應用圓角。現在添加一個UILabel作爲子視圖到這個UIView &的位置,使得底部的2個圓角被標籤覆蓋。這樣,你得到你所需要的效果...

+0

,並確保的UIView和的UILabel具有相同的顏色。 – chatur 2012-01-27 14:13:38

+0

ofcourse,thats給定。否則告訴很容易看到... – 2012-01-27 14:14:43

25

思想建立一個UIBezierPath我會發布完整的代碼包括貝塞爾路徑。

CGRect bounds = label.bounds; 
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds 
                    byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) 
                     cornerRadii:CGSizeMake(5.0, 5.0)]; 

CAShapeLayer *maskLayer = [CAShapeLayer layer]; 
maskLayer.frame = bounds; 
maskLayer.path = maskPath.CGPath; 

label.layer.mask = maskLayer; 

對於雨燕4.0:

let bounds: CGRect = label.bounds 
let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: ([.topLeft, .topRight]), cornerRadii: CGSize(width: 5.0, height: 5.0)) 
let maskLayer = CAShapeLayer() 
maskLayer.frame = bounds 
maskLayer.path = maskPath.cgPath 
label.layer.mask = maskLayer