iOS-CGContextStrokePath/CGContextDrawPath删除黑色背景色



我正在画一条直线。我已经得到了它,所以它画了破折号,但这个黑色的背景颜色仍然存在。我似乎对其他问题有很多答案,但都不起作用。

苹果的文档似乎指向填充颜色,并使用CGContextFillPath或CGContextDrawPath,但这两种方法都不起作用,虚线的背景仍然是黑色的。

- (void)drawRect:(CGRect)rect {
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    GLFloat lines[] = {self.frame.size.width, self.frame.size.width*2};
    CGFloat grey[4] = {0.6f, 0.6f, 0.6f, 1.0f};
    CGContextSetStrokeColor(contextRef, grey);
    CGContextSetFillColorWithColor(contextRef, [[UIColor clearColor] CGColor]);
    CGContextSetLineDash(contextRef, 0, lines, 2);
    CGContextSetLineWidth(contextRef, self.frame.size.width);
    CGContextBeginPath(contextRef);
    CGContextMoveToPoint(contextRef, 0, 0);
    CGContextAddLineToPoint(contextRef, 0, self.frame.size.height);
    CGContextDrawPath(contextRef, kCGPathFillStroke);
}

手动将此视图添加到视图层次结构时,只需确保设置了背景颜色。例如,如果您正在使用initWithFrame初始化视图,则使用该方法设置背景颜色:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

或者,在添加视图时,在那里设置背景颜色:

CustomView *customView = [[CustomView alloc] initWithFrame:frame];
customView.backgroundColor = [UIColor clearColor];
[self.view addSubview:customView];

最新更新