Raptor
Raptor

Reputation: 54260

Draw lines in a UIView, with transparent background

I have the following codes to draw lines in a UIView. But once I start drawing, the view becomes dark grey. How can I make the background transparent? I already set the backgroundColor to clearColor, but the background is still dark gray. What did I miss?

@interface CanvasView () {
    UIColor *colorLine;
    UIBezierPath *pathBezier;
}

@end

@implementation CanvasView
@synthesize imgCached;

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self) {
        self.backgroundColor = [UIColor clearColor];
        [self setMultipleTouchEnabled:NO];
        pathBezier = [[UIBezierPath alloc] init];
        pathBezier.lineWidth = 5;

        colorLine = [UIColor redColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [self.imgCached drawInRect:rect];
    [pathBezier stroke];
}

- (void)drawCache {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0.0);
    [colorLine setStroke];
    if(!self.imgCached) {
        UIBezierPath *rectpath = [UIBezierPath bezierPathWithRect:self.bounds];
        [rectpath fill];
    }
    [self.imgCached drawAtPoint:CGPointZero];
    [pathBezier stroke];
    self.imgCached = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

- (void)clearGraphics {
    self.imgCached = nil;
    [pathBezier removeAllPoints];
    [self setNeedsDisplay];
}

#pragma mark - Touch methods
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    [pathBezier moveToPoint:[touch locationInView:self]];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    [pathBezier addLineToPoint:[touch locationInView:self]];

    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    [pathBezier addLineToPoint:p];
    [self drawCache];
    [self setNeedsDisplay];
    [pathBezier removeAllPoints];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesEnded:touches withEvent:event];
}

p.s. the imgCached is:

@property (nonatomic, strong) UIImage *imgCached;

Upvotes: 1

Views: 1157

Answers (1)

Guy Kogus
Guy Kogus

Reputation: 7351

Replace your drawRect: and drawCache methods with the following:

- (void)drawRect:(CGRect)rect {
    [self.imgCached drawInRect:rect];
    [colorLine setStroke];
    [pathBezier stroke];
}

- (void)drawCache {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    [colorLine setStroke];
    [self.imgCached drawAtPoint:CGPointZero];
    [pathBezier stroke];
    self.imgCached = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

Upvotes: 3

Related Questions