iPhone CGContext:用两种不同的颜色画线



我想用CGContext画一条不同颜色的线。

这是我的代码

   CGSize size = CGSizeMake(200, 200);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextMoveToPoint(context, 1, 1);
    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextAddLineToPoint(context, 50, 50);
    CGContextAddLineToPoint(context, 100, 50);
    CGContextStrokePath(context);
    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    CGContextAddLineToPoint(context, 200, 100);
    CGContextStrokePath(context);

我正在尝试此代码,其返回错误:

<Error>: CGContextAddLineToPoint: no current point.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 1, 1);
CGContextAddLineToPoint(context, 100, 100);
CGContextStrokePath(context); // and draw blue line
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextMoveToPoint(context, 100, 100);
CGContextAddLineToPoint(context, 200, 100);     
CGContextStrokePath(context); // draw red line

以下代码可能会对您有所帮助:

CGSize size = CGSizeMake(200, 200);
//UIGraphicsBeginImageContextWithOptions(size, NO, 0); //comment this line,  if you want a image, see bottom two line.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextMoveToPoint(context, 1, 1);   //MoveToPoint First
CGContextAddLineToPoint(context, 50, 50);
CGContextAddLineToPoint(context, 100, 50);
CGContextStrokePath(context);
CGContextBeginPath(context);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGContextMoveToPoint(context, 100, 50);   //MoveToPoint First
CGContextAddLineToPoint(context, 200, 100);
CGContextStrokePath(context);
//UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext(); //if you just need a image
//UIGraphicsEndImageContext(); //match UIGraphicsBeginImageContextWithOptions, if need a image

最新更新