Written by
小小厨师
on
on
关于drawRect绘图重叠的问题
当我们在drawRect
中绘图时,如果没有对当前view设置过背景色,或者未设置opaque
属性值,会发现绘制的图形会重叠,这是因为drawRect
默认不清除先前的内容。
drawRect
清除操作取决于是否有填充操作;
drawRect
清除内容机制如下:
context清理
UIView有个属性opaque
, 默认为 YES。UIView 还有个属性clearsContextBeforeDrawing
, 默认为 YES,官方文档解释如下:
@property(nonatomic,getter=isOpaque) BOOL opaque; // default is YES. opaque views must fill their entire bounds or the results are undefined. the active CGContext in drawRect: will not have been cleared and may have non-zeroed pixels
@property(nonatomic) BOOL clearsContextBeforeDrawing; // default is YES. ignored for opaque views. for non-opaque views causes the active CGContext in drawRect: to be pre-filled with transparent pixels
- 当opaque=YES时, 系统调用-drawRect:前,不会清除以前内容
- 当opaque= NO时, 系统调用-drawRect:前,会根据
clearsContextBeforeDrawing
属性做不同行为- clearsContextBeforeDrawing = YES, 则清除内容,以透明像素填充。
- clearsContextBeforeDrawing = NO, 则不清除内容。
backgroundColor填充
backgroundColor
填充context,默认为nil。
- 当设置
backgroundColor
后,系统每次会用设置的对应颜色填充context,也就清除了之前内容。