Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting A CGContext Transparent Background

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 background shows thru. Here's my test code:

(void)drawRect:(CGRect)rect {     CGContextRef context = UIGraphicsGetCurrentContext();     CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);     CGContextSetAlpha(context,0.0);     CGContextFillRect(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); } 

Any ideas?

like image 925
Jim B Avatar asked Jan 24 '10 01:01

Jim B


1 Answers

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]; } 
like image 126
David Kanarek Avatar answered Sep 18 '22 13:09

David Kanarek