iPhone CGContext: drawing two lines with two different colors

前端 未结 4 1195
终归单人心
终归单人心 2021-02-05 21:41

I am having some troubles using the CGContext with an iPhone app. I am trying to draw several lines with different colors, but all the lines always end up having the color which

4条回答
  •  遥遥无期
    2021-02-05 21:59

    If you are interested in the way it looks in a loop:

    - (void)drawRect:(CGRect)rect {        
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetLineWidth(context, 2.0);
    
        CGPoint startingPoint = [[pointsArray objectAtIndex:0] CGPointValue];
        CGContextMoveToPoint(context, startingPoint.x, startingPoint.y); //start at this point
    
        for (int i = 1; i < [pointsArray count]; i++) {
            CGContextBeginPath(context);
            //start at the previous point
            CGContextMoveToPoint(context, 
                   [[pointsArray objectAtIndex:i-1] CGPointValue].x, 
                   [[pointsArray objectAtIndex:i-1] CGPointValue].y);
    
            CGPoint point = [[pointsArray objectAtIndex:i] CGPointValue];
            if (point.y < 50) { // if y is less then 50 use red color
                CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
            } else { // else use blue color
                CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    
            }
            CGContextAddLineToPoint(context, point.x, point.y); //draw to this point
            CGContextStrokePath(context);
        }
    }
    

提交回复
热议问题