自定義 UIView 子類在 drawRect: 中繪製文本,背景呈現黑色,需改為透明或白色。
UIView 默認背景色為透明 (clearColor),但若父視圖背景為黑、或繪圖上下文未清理、或未設置 opaque = NO,可能顯示為黑色。此外 drawRect: 中未繪製背景時,顯示的是父視圖內容或未定義內容。
在初始化方法中設置:
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 方案 1:透明背景 (默認,但顯式設置更清晰)
self.backgroundColor = [UIColor clearColor];
// 關鍵:告訴系統視圖非不透明,允許混合
self.opaque = NO;
// 方案 2:白色背景
// self.backgroundColor = [UIColor whiteColor];
// self.opaque = YES; // 不透明可優化性能
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 1. 繪製背景 (白色或透明)
// 透明:不需填充,但需確保 opaque=NO
// 白色:
[[UIColor whiteColor] setFill];
UIRectFill(rect); // 填充整個 rect
// 2. 繪製文本/其他內容
// ...
}
| 屬性 | 值 | 效果 |
|---|---|---|
backgroundColor | [UIColor clearColor] | 透明,顯示父視圖內容 |
backgroundColor | [UIColor whiteColor] | 白色實心背景 |
opaque | NO (默認) | 允許透明混合,**透明背景必須設置** |
opaque | YES | 聲明視圖完全不透明,系統優化繪製 (不混合) |
clearsContextBeforeDraw | YES (默認) | 每次 drawRect 前自動清空上下文 (填充背景色) |
opaque = NO:透明背景視圖默認 opaque=YES 時,系統不進行混合,直接顯示未初始化的顯存內容 (常為黑色)。backgroundColor。backgroundColor 且 clearsContextBeforeDraw=YES,系統會自動填充,手動再填一次雖無害但多餘。**設置 self.backgroundColor = [UIColor clearColor]; self.opaque = NO;** 即可獲得透明背景。若需白色背景,設置 whiteColor 並 opaque = YES 以獲取性能優化。在 drawRect: 中專注繪製前景內容,背景交給屬性系統管理。