2012-11-23 58 views
13

下面的代碼很好地創建了一個由CGRect(rectRect)定義的圓角矩形。填充後無法描邊路徑

它很好,但我沒有中風。任何想法爲什麼我看不到中風?

-(void)drawRect:(CGRect)rect { 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 

    CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.4); 
    CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1); 
    CGContextSetLineWidth(ctx, 4.0); 

    float fw, fh; 
    rect = rectRect; 
    float ovalWidth = 12; 
    float ovalHeight = 12; 

    if (ovalWidth == 0 || ovalHeight == 0) { 
     CGContextAddRect(ctx, rect); 
     return; 
    } 

    CGContextTranslateCTM (ctx, CGRectGetMinX(rect), CGRectGetMinY(rect)); 
    CGContextScaleCTM (ctx, ovalWidth, ovalHeight); 
    fw = CGRectGetWidth (rect)/ovalWidth; 
    fh = CGRectGetHeight (rect)/ovalHeight; 
    CGContextMoveToPoint(ctx, fw, fh/2); 
    CGContextAddArcToPoint(ctx, fw, fh, fw/2, fh, 1); 
    CGContextAddArcToPoint(ctx, 0, fh, 0, fh/2, 1); 
    CGContextAddArcToPoint(ctx, 0, 0, fw/2, 0, 1); 
    CGContextAddArcToPoint(ctx, fw, 0, fw, fh/2, 1); 
    CGContextClosePath(ctx); 

    CGContextFillPath(ctx); 
    CGContextStrokePath(ctx); 

} 

回答

44

繪製路徑時,無論是通過撫摸還是填充路徑,圖形上下文都將其路徑重置爲空。因此,在您致電CGContextFillPath後,上下文沒有中途的路徑。

,而不是試圖填補路徑,然後中風它,你可以使用CGContextDrawPath函數調用一次一舉兩得:

CGContextDrawPath(ctx, kCGPathFillStroke); 

kCGPathFillStroke不斷告訴核芯顯卡填補了路徑,然後中風它。

在另一方面,你可以使用UIBezierPathUIColor減少代碼基本量:

-(void)drawRect:(CGRect)rect { 
    [[UIColor colorWithWhite:0 alpha:0.4] setFill]; 
    [[UIColor whiteColor] setStroke]; 

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rectRect cornerRadius:12]; 
    path.lineWidth = 4; 
    [path fill]; 
    [path stroke]; 
} 
+1

感謝。這就是我一直在尋找的東西。 – Mrwolfy

+0

哦,順便說一下,UIBezierPath選項是否是高性能修復?它當然完美。或者我應該在別處尋找。 – Mrwolfy

+0

在儀器告訴你瓶頸在哪裏之前,不要擔心性能。 –