0

我正在尝试绘制一个显示在 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();
    }

但它在单线上画了一条对角线。已显示在下图中

我期待画一条曲线!使用核心图形 在此处输入图像描述

4

2 回答 2

1

首先,你不能CGContextAddLineToPoint进入循环。删除(仅)循环,并在 eg 中创建另一个循环viewDidLoad,在每次迭代时,调用-(void)createGraph给出最后一个点和下一个点。现在您将分配给的最后一个点CGContextMoveToPoint,以及您将分配给的下一个点CGContextAddLineToPoint。顺便说一句,在CGContextBeginPath(context);后面加上CGContextSetLineWidth(context, 2.0);

于 2012-07-18T13:36:05.193 回答
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;
}
于 2012-07-18T14:48:24.000 回答