Setting A CGContext Transparent Background

后端 未结 8 759
长发绾君心
长发绾君心 2020-12-08 09:15

I am still struggling with drawing a line with CGContext. I have actually go to line to draw, but now I need the background of the Rect to be transparent so the existing ba

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 09:45

    After UIGraphicsGetCurrentContext() call CGContextClearRect(context,rect)

    Edit: Alright, got it.

    Your custom view with the line should have the following:

    - (id)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            [self setBackgroundColor:[UIColor clearColor]];
        }
        return self;
    }
    
    - (void)drawRect:(CGRect)rect {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextClearRect(context, rect);
        CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
        CGContextSetLineWidth(context, 5.0);
        CGContextMoveToPoint(context, 100.0,0.0);
        CGContextAddLineToPoint(context,100.0, 100.0);
        CGContextStrokePath(context);
    }
    

    My test used this as a very basic UIViewController:

    - (void)viewDidLoad {
        [super viewDidLoad];
        UIImageView *v = [[UIImageView alloc] initWithFrame:self.view.bounds];
        [v setBackgroundColor:[UIColor redColor]];
        [self.view addSubview:v];
        TopView *t = [[TopView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:t];
        [v release];
        [t release];
    }
    

提交回复
热议问题