关于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

backgroundColor填充

backgroundColor填充context,默认为nil。