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
似乎是造成這個問題。
爲什麼你不繪製繪製矩形的背景? – Wain 2015-02-11 07:36:59
@Wain - 我猜是因爲我在一段時間後添加了繪圖代碼,所以我沒有考慮它。 – 2015-02-11 07:41:43