在UIView中绘制线条,具有透明背景

时间:2014-11-14 11:17:39

标签: ios uiview uibezierpath

我有以下代码在UIView中绘制线条。但是一旦我开始绘画,视图就会变成深灰色。如何使背景透明?我已将backgroundColor设置为clearColor,但背景仍为深灰色。我错过了什么?

@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。 imgCached是:

@property (nonatomic, strong) UIImage *imgCached;

1 个答案:

答案 0 :(得分:2)

drawRect:drawCache方法替换为以下内容:

- (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();
}