2015-02-11 155 views
2

我有一個UIButton子類,我使用drawRect:繪製邊界。當選擇按鈕時,我想要改變背景顏色,並刪除邊框。 (手工繪製的邊界,因爲有時我只需要在一側的一個邊界)CGContextClearRect導致背景顏色爲黑色

出於某種原因,當我使用CGContextClearRect刪除已經被抽我得到一個黑色的背景,而不是我設置的顏色的邊框:

- (void)setSelected:(BOOL)selected { 
    [super setSelected:selected]; 

    if (selected) { 
     self.allOff = YES; 
     self.backgroundColor = self.selectedColor; 
     [self setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected]; 
    } else { 
     self.allOff = NO; 
     self.backgroundColor = self.defaultColor; 
     [self setTitleColor:[OTAColors colorWithRed:163 green:163 blue:163] forState:UIControlStateNormal]; 
    } 

} 

- (void)_setup { 

    self.opaque = NO; 

    self.defaultColor = [[UIColor whiteColor] colorWithAlphaComponent:0.99]; 
    self.selectedColor = [[OTAColors colorWithRed:33 green:59 blue:70] colorWithAlphaComponent:0.99]; 

    self.backgroundColor = self.defaultColor; 
    [self setTitleColor:[OTAColors colorWithRed:163 green:163 blue:163] forState:UIControlStateNormal]; 
    self.titleLabel.font = [UIFont fontWithName:OTAFontPFDinTextCondProMedium size:20]; 
    self.titleLabel.textAlignment = NSTextAlignmentCenter; 

} 

- (void)drawRect:(CGRect)rect { 

    CGFloat borderWidth = 0.7f; 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(ctx, borderWidth); 
    UIColor *borderColor = self.borderColor ? self.borderColor : [UIColor blackColor]; 
    CGContextSetStrokeColorWithColor(ctx, borderColor.CGColor); 

    if (!self.allOff) { 
     // Left 
     if (self.left) { 
      CGContextMoveToPoint(ctx, 0, 0); 
      CGContextAddLineToPoint(ctx, 0,rect.size.height); 
      CGContextStrokePath(ctx); 
     } 

     // Right 
     if (self.right) { 
      CGContextMoveToPoint(ctx, rect.size.width, 0); 
      CGContextAddLineToPoint(ctx, rect.size.width,rect.size.height); 
      CGContextStrokePath(ctx); 
     } 

     // Top 
     if (self.top) { 
      CGContextMoveToPoint(ctx, 0, 0); 
      CGContextAddLineToPoint(ctx, rect.size.width,0); 
      CGContextStrokePath(ctx); 
     } 

     // Bottom 
     if (self.bottom) { 
      CGContextMoveToPoint(ctx, 0, rect.size.height); 
      CGContextAddLineToPoint(ctx, rect.size.width,rect.size.height); 
      CGContextStrokePath(ctx); 
     } 
    } else { 
     CGContextClearRect(ctx, rect); 
    } 

} 

任何想法,爲什麼會發生這種情況? CGContextClearRect似乎是造成這個問題。

+0

爲什麼你不繪製繪製矩形的背景? – Wain 2015-02-11 07:36:59

+0

@Wain - 我猜是因爲我在一段時間後添加了繪圖代碼,所以我沒有考慮它。 – 2015-02-11 07:41:43

回答

2

調用clear rect會清除所有內容,因此它將恢復爲默認的黑色內容。相反,您應該先用背景顏色填充矩形,然後在其後爲邊框繪製適當的線條。

+0

完成,它的工作。謝謝! – 2015-02-11 08:09:14