【问题标题】:Drawing graph line using Core Graphics使用 Core Graphics 绘制图形线
【发布时间】:2012-07-18 13:33:25
【问题描述】:

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

但它在单线上绘制对角线。如下图所示

我期待画一条曲线!使用核心图形

【问题讨论】:

    标签: iphone ios ipad graph core-graphics


    【解决方案1】:

    首先,您不能将CGContextAddLineToPoint 放入循环中。删除(仅)循环,并在例如viewDidLoad,在每次迭代中,调用-(void)createGraph 给出最后一点和下一点。现在您将分配给CGContextMoveToPoint 的最后一个点,您将分配给CGContextAddLineToPoint 的下一个点。顺便在CGContextSetLineWidth(context, 2.0);后面加上CGContextBeginPath(context);

    【讨论】:

      【解决方案2】:
      - (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;
      }
      

      【讨论】:

      • @kiran - 现在试试这个代码......对不起我的错误,我把你的问题弄错了...... :-(
      • 谢谢...昨天我完全错了...很高兴知道它对您有帮助:-)
      • 是的,它正在加载它的工作当我从一个视图导航并返回它改变它的位置时。
      • 是的,因为每次您都会为 X 和 Y 坐标生成随机数。