gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:56:09 25 4
gpt4 key购买 nike

我有以下代码在 UIView 中画线.但是一旦我开始绘画, View 就会变成深灰色。我怎样才能使背景透明?我已经设置了backgroundColorclearColor ,但背景仍然是深灰色。我错过了什么?

@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;

最佳答案

更换您的 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();
}

关于ios - 在 UIView 中绘制线条,具有透明背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26928788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com