我需要自定义一个表的单元格,创建两个透明条带,一个对应于UITableViewCell的上边缘,另一个对应于下边缘。这些条带应该是透明的,以便看到下面视图的颜色(浅黄色)。 我创建了一个UITableViewCell的子类,我构建了LayoutSubviews()方法来绘制条带,这是错的?我收到了这个错误:
<Error>: CGContextBeginPath: invalid context 0x0
<Error>: CGContextMoveToPoint: invalid context 0x0
<Error>: CGContextAddLineToPoint: invalid context 0x0
<Error>: CGContextSetLineWidth: invalid context 0x0
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
<Error>: CGContextMoveToPoint: invalid context 0x0
<Error>: CGContextAddLineToPoint: invalid context 0x0
<Error>: CGContextSetLineWidth: invalid context 0x0
<Error>: CGContextSetFillColorWithColor: invalid context 0x0
这是CustomCell.m中的代码:
-(void) layoutSubviews{
[super layoutSubviews];
CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctxt);
CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.origin.y);
CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.origin.y);
CGContextSetLineWidth(ctxt, 5);
CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor);
CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.size.height);
CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.size.height);
CGContextSetLineWidth(ctxt, 5);
CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor);
CGContextStrokePath(ctxt);
}
答案 0 :(得分:3)
layoutSubviews
是绘制内容的错误方法。那里没有绘图上下文。将代码移至drawRect:
:
- (void)drawRect:(CGRect)rect {
[super drawRect: rect];
CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctxt);
CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.origin.y);
CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.origin.y);
CGContextSetLineWidth(ctxt, 5);
CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor);
CGContextMoveToPoint(ctxt, self.bounds.origin.x, self.bounds.size.height);
CGContextAddLineToPoint(ctxt, self.bounds.size.width, self.bounds.size.height);
CGContextSetLineWidth(ctxt, 5);
CGContextSetFillColorWithColor(ctxt, [UIColor clearColor].CGColor);
CGContextStrokePath(ctxt);
}
答案 1 :(得分:2)
(void) drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *color = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextSetLineWidth(context, 3.0);
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor); //CGContextSetRGBFillColor doesn't work either
CGContextBeginPath(context);
CGContextMoveToPoint(context, 100.0, 60.0);
CGRect rectangle = {100.0, 60.0, 120.0, 120.0};
CGContextAddRect(context, rectangle);
CGContextStrokePath(context);
CGContextFillPath(context);
}