只需对您的代码进行一些更正:
-(void)drawLineFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint{
UIGraphicsBeginImageContext(YOUR_IMAGEVIEW.image.size);
[YOUR_IMAGEVIEW.image drawInRect:CGRectMake(0, 0, YOUR_IMAGEVIEW.image.size.width, YOUR_IMAGEVIEW.image.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), startPoint.x, startPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), endPoint.x, endPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
[YOUR_IMAGEVIEW setImage:UIGraphicsGetImageFromCurrentImageContext()];
UIGraphicsEndImageContext();
}
YOUR_IMAGEVIEW 是您正在绘制的图像视图的出口。
如您所见 - 您只需将起点和终点发送到此方法!像 1-2-3 一样简单。
编辑 1
如何使用它?声明一个全局 CGPoint “startPoint”;
然后说:
//___________________________________________________
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:YOUR_IMAGEVIEW];
}
//___________________________________________________
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint nextPoint = [touch locationInView:YOUR_IMAGEVIEW];
[self drawLineFromPoint:startPoint toPoint:nextPoint];
startPoint = nextPoint;
}
编辑 2
这是另一种表达观点的方法:
- (void)drawGraphMethod{
NSMutableArray *pointsArr = [[[NSMutableArray alloc]init]autorelease];
//now you should add the needed points to your array
//I have no idea what graph do you have, so I just
//put there some random points that will look like a graph
[pointsArr addObject:[NSValue valueWithCGPoint:CGPointMake(30.0, 10.0)]];
[pointsArr addObject:[NSValue valueWithCGPoint:CGPointMake(40.0, 26.0)]];
[pointsArr addObject:[NSValue valueWithCGPoint:CGPointMake(70.0, 55.0)]];
[pointsArr addObject:[NSValue valueWithCGPoint:CGPointMake(80.0, 88.0)]];
[pointsArr addObject:[NSValue valueWithCGPoint:CGPointMake(90.0, 33.0)]];
[pointsArr addObject:[NSValue valueWithCGPoint:CGPointMake(130.0, 100.0)]];
//well, you can store only objects, that's why I used NSValue.
//it's not hard to cenvert it back
//now parse the array
for (int i = 0; i < pointsArr.count-1; i++) {
CGPoint startPoint = [[pointsArr objectAtIndex:i] CGPointValue];
CGPoint nextPoint = [[pointsArr objectAtIndex:i+1] CGPointValue];
[self drawLineFromPoint:startPoint toPoint:nextPoint];
}
}