我正在尝试绘制一个在imageview上显示的随机图表,我尝试使用此代码
-(void)createGraph{
UIGraphicsBeginImageContext(self.drawImage.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 2.0);
int i = 0;
while (i<=20) {
int r = rand() % 100;
CGContextMoveToPoint(context, 20, 320);
CGContextAddLineToPoint(context, linePoint.x+20+i*r, linePoint.y+320-i*r);
CGContextStrokePath(context);
i++;
NSLog(@"random value %d",r);
}
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
}
但是它在单线上绘制了一条对角线。已在下图中显示
我期待画一条图线!使用coregraphics
答案 0 :(得分:1)
首先,您不能将CGContextAddLineToPoint
放入循环中。删除(仅)循环,并在例如另一个循环中viewDidLoad
,在每次迭代时,调用-(void)createGraph
给出最后一个点和下一个点。现在,您将分配给CGContextMoveToPoint
的最后一点,以及您将给予CGContextAddLineToPoint
的下一个点。顺便说一下,在CGContextBeginPath(context);
CGContextSetLineWidth(context, 2.0);
答案 1 :(得分:1)
- (void)viewDidLoad
{
//X_Line, Y_Line, x and y are integer variables
X_Line = 20;
Y_Line = 320;
for(int i=0; i<10; i++)
{
x = x + arc4random() % 100;
y = x + arc4random() % 100;
[self createGraph];
}
}
-(void)createGraph
{
UIGraphicsBeginImageContext(imgView.frame.size);
[imgView.image drawInRect:CGRectMake(0, 0, imgView.frame.size.width, imgView.frame.size.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetLineWidth(context, 2.0);
CGContextMoveToPoint(context, X_Line, Y_Line);
CGContextAddLineToPoint(context, x , y);
CGContextStrokePath(context);
imgView.image = UIGraphicsGetImageFromCurrentImageContext();
X_Line = x;
Y_Line = y;
}