views:

1312

answers:

1

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?

+3  A: 

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];
}
David Kanarek
Background is black, must be the iphone background. I'm actually trying to draw on top of a UIView.
Jim B
I don't quite follow. Are you sure you added the UIView to the superview? Is this drawRect in the UIView you want to draw on top of, or in a different one? Did you set a background color for this UIView accidentally?
David Kanarek
Thanks for the questions. I would expect that IM added the UIView to it's superview. The draw rectangle is definitely in the view, since the line was drawn properly. Yes I have set a background into the UIView, it's that background I want to show thru. All I'm trying to do is draw a line on top of an existing view. Frustrated in Seattle.
Jim B
Fantastic, it really works. I really appreciate your effort.
Jim B