2012-08-26 61 views
0

嗨,下面的代碼使一個灰色的小矩形與一個黑暗的邊框。角落收音機不工作,我不明白爲什麼,我試過應用maskToBounds = true,但這只是隱藏整個對象...CAShapeLayer cornerRadius不工作在UIBezierPath

我該如何實現這一目標?由於

CGRect r = CGRectMake(conX, conY, 220, 50); 
    UIBezierPath* conPath = [UIBezierPath bezierPathWithRect:r]; 
    CAShapeLayer* conLayer = [CAShapeLayer layer]; 
    conLayer.path = conPath.CGPath; 
    conLayer.cornerRadius = 5.0; 
    UIColor *bg = [UIColor colorWithWhite:1 alpha:0.7]; 
    [conLayer setFillColor:bg.CGColor]; 
    [conLayer setStrokeColor:[UIColor grayColor].CGColor]; 
    [[self layer] addSublayer:conLayer]; 

回答

6

UPDATE:

您可以簡單地使用UIBezierPath(roundedRect: CGRect, cornerRadius: CGFloat).CGPath來創建圓矩形路徑


我建議採用圓矩形路徑,而不是:

CGRect r = { .size = { 220.0f, 50.0f } } ; 

CAShapeLayer * layer = [ CAShapeLayer layer ] ; 
layer.path = CGPathCreateRoundRect(r, 5.0f) ; 

其中CGPathCreateRoundRect()

CGPathRef CGPathCreateRoundRect(const CGRect r, const CGFloat cornerRadius) 
{ 
    CGMutablePathRef p = CGPathCreateMutable() ; 

    CGPathMoveToPoint(p, NULL, r.origin.x + cornerRadius, r.origin.y) ; 

    CGFloat maxX = CGRectGetMaxX(r) ; 
    CGFloat maxY = CGRectGetMaxY(r) ; 

    CGPathAddArcToPoint(p, NULL, maxX, r.origin.y, maxX, r.origin.y + cornerRadius, cornerRadius) ; 
    CGPathAddArcToPoint(p, NULL, maxX, maxY, maxX - cornerRadius, maxY, cornerRadius) ; 

    CGPathAddArcToPoint(p, NULL, r.origin.x, maxY, r.origin.x, maxY - cornerRadius, cornerRadius) ; 
    CGPathAddArcToPoint(p, NULL, r.origin.x, r.origin.y, r.origin.x + cornerRadius, r.origin.y, cornerRadius) ; 

    return p ; 
} 
+0

如果它是你想要的遮罩效果,請將圖層的__mask__屬性設置爲具有圓形矩形路徑的形狀圖層 – nielsbot

+0

Thanks Niels thats awesome mate! :d) – Baconbeastnz

相關問題