我只是在学习核心图形。 所以我创建了一个新项目,包括一个UIView类。 现在我在我的UIView实现文件中有以下代码
-(id) initWithCoder:(NSCoder*)sourceCoder
{
if( ( self = [super initWithCoder:sourceCoder]))
{
//place any other initialization here
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context,4);
CGContextSetStrokeColorWithColor(context, myColor.CGColor);
CGContextMoveToPoint(context,startPoint.x , startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextStrokePath(context);
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touchPoint = [touches anyObject];
startPoint = [touchPoint locationInView:self];
endPoint = [touchPoint locationInView:self];
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
endPoint=[touch locationInView:self];
[self setNeedsDisplay];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
endPoint = [touch locationInView:self];
[self setNeedsDisplay];
}
但它只是创建了一条线,如果我再次尝试绘制,那么前一行就会丢失。
但我想前一行不应该丢失,我该怎么做?
答案 0 :(得分:0)
将视图的clearsContextBeforeDrawing
property设置为NO
。
答案 1 :(得分:0)
将UIImageView设置为背景,使用以下内容保存上下文(行)
CGContextStrokePath(UIGraphicsGetCurrentContext());
<your imageView>.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();