CGContextRef
之前在项目中遇到画凹型View,代码如下:
(void)drawRect:(CGRect)rect {
floatx = rect.origin.x;
floaty = rect.origin.y;
floatw = rect.size.width;
floath = rect.size.height;
CGContextRef context = UIGraphicsGetCurrentContext();
//设置绘制的颜色
CGContextSetRGBStrokeColor(context,1,0,0,0);
//设置绘制直线、边框时的线条宽度
CGContextSetLineWidth(context, 1.0);
if (_arcViewColor) {
//设置绘制的view的颜色
CGContextSetFillColorWithColor(context, _arcViewColor.CGColor);
}else{
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
}
// 开始一个新的子路径点
CGContextMoveToPoint(context,x,y);
// 添加一条直线段从当前指向的(x,y)。
CGContextAddLineToPoint(context,x,h);
CGContextAddLineToPoint(context,w,h);
CGContextAddLineToPoint(context,w,y);
CGContextAddLineToPoint(context,w,y);
CGContextAddLineToPoint(context,w/2,h);
CGContextAddLineToPoint(context,x,y);
//使用指定模式绘制当前CGContextRef中所包含的路径,
//void CGContextDrawPath(CGContextRef__nullable c, CGPathDrawingMode mode)
/**
typedef CF_ENUM (int32_t, CGPathDrawingMode) {
kCGPathFill,//只有填充(非零缠绕数填充),不绘制边框
kCGPathEOFill,//奇偶规则填充(多条路径交叉时,奇数交叉填充,偶交叉不填充)
kCGPathStroke, // 只有边框
kCGPathFillStroke, // 既有边框又有填充
kCGPathEOFillStroke // 奇偶填充并绘制边框
};
**/
CGContextDrawPath(context, kCGPathFillStroke);
}
问题:自定义的绘制View图形有时候显示不出来
原因: 在需要隐藏view时,为当前的view设置height为0,当View的size为0时,绘制view时是不会走drawRect方法的。所以在刚进入时为空数据,再转为有数据时,当前的view 不会走drawRect。
DrawRect调用时机
1、如果在UIView初始化时没有设置rect大小,将直接导致drawRect不被自动调用。
drawRect 调用是在Controller->loadView, Controller->viewDidLoad 两方法之后掉用的.所以不用担心在 控制器中,这些View的drawRect就开始画了.这样可以在控制器中设置一些值给View(如果这些View draw的时候需要用到某些变量 值).
2、该方法在调用sizeToFit后被调用,所以可以先调用sizeToFit计算出size。然后系统自动调用drawRect:方法。
3、通过设置contentMode属性值为UIViewContentModeRedraw。那么将在每次设置或更改frame的时候自动调用drawRect:。
4、直接调用setNeedsDisplay,或者setNeedsDisplayInRect:触发drawRect:,但是有个前提条件是rect不能为0
网友评论