2010-06-15 22 views
10

Tengo algunos problemas al utilizar CGContext con una aplicación de iPhone. Estoy tratando de dibujar varias líneas con diferentes colores, pero todas las líneas siempre terminan teniendo el color que se utilizó por última vez. Probé varios enfoques, pero no he tenido suerte.iPhone CGContext: dibujo dos líneas con dos colores diferentes

Configuré un pequeño proyecto de muestra para tratar ese problema. Este es mi código, lo uso en el método drawRect. Estoy tratando de sacar una roja y una línea azul:

- (void)drawRect:(CGRect)rect{ 
    NSLog(@"drawrect!"); 
    CGContextRef bluecontext = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(bluecontext, 2.0); 
    CGContextSetStrokeColorWithColor(bluecontext, [UIColor blueColor].CGColor); 
    CGContextMoveToPoint(bluecontext, 1, 1); 
    CGContextAddLineToPoint(bluecontext, 100, 100); 
    CGContextSetStrokeColorWithColor(bluecontext, [UIColor redColor].CGColor); 
    CGContextAddLineToPoint(bluecontext, 200, 100); 
    CGContextStrokePath(bluecontext); 
} 

gracias por su ayuda

Respuesta

22

Inserta este código justo antes de configurar el color del trazo el segundo tiempo:

CGContextStrokePath(bluecontext); 
CGContextBeginPath(bluecontext); 

Todo el Las llamadas AddLine y AddOther están creando una ruta. La ruta se dibuja con una llamada como StrokePath, utilizando los últimos colores configurados y otros atributos. Está intentando dibujar dos rutas separadas, por lo que debe llamar a Begin y Stroke para cada ruta. Comenzar es algo implícito cuando comienzas a dibujar, aunque no hace daño llamarlo tú mismo. El flujo básico de dibujo es:

CGContextBeginPath(bluecontext); // clears any previous path 
// add lines, curves, rectangles, etc... 
CGContextStrokePath(bluecontext); // renders the path 
+0

Gracias, por lo que este funciona básicamente al hecho, de que tengo que hacer un camino con un color, antes de que yo dibujar un camino con otro color? Crear dos contextos, uno para las líneas azules y otro para las rojas no funciona, porque están usando el mismo contexto al final? – phonecoddy

+2

Sí, por cada cambio de color debe dibujar la ruta y borrarla. Puedes hacerlo todo en el mismo contexto. – drawnonward

2

Creo que esto podría estar funcionando.

CGContextRef bluecontext = UIGraphicsGetCurrentContext(); 
CGContextSetLineWidth(bluecontext, 2.0); 
CGContextSetStrokeColorWithColor(bluecontext, [UIColor blueColor].CGColor); 
CGContextMoveToPoint(bluecontext, 1, 1); 
CGContextAddLineToPoint(bluecontext, 100, 100); 

CGContextStrokePath(bluecontext); // draw blue line 


CGContextSetStrokeColorWithColor(bluecontext, [UIColor redColor].CGColor); 
CGContextAddLineToPoint(bluecontext, 200, 100); 

CGContextStrokePath(bluecontext); // and draw red line 
12

Eso es lo que necesita.

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextClearRect(context, rect); 
CGContextSetLineWidth(context, 2.0); 

CGContextBeginPath(context); 
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor); 
CGContextMoveToPoint(context, 1, 1); 
CGContextAddLineToPoint(context, 100, 100); 
CGContextStrokePath(context); // and draw orange line} 

CGContextBeginPath(context); 
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 
CGContextMoveToPoint(context, 100, 100); 
CGContextAddLineToPoint(context, 200, 100);  
CGContextStrokePath(context); // draw blue line 
1

Si usted está interesado en la forma en que se ve en un bucle:

- (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); 
    } 
} 
+0

¿Qué es el transformPoint en tu respuesta? –

+0

Buen punto, gracioso cómo han pasado 3 años y nadie pensó en preguntar eso. Estoy bastante seguro de que puedes usar "punto" para reemplazar "transformPoint". Lo probaré más tarde hoy para verificarlo. @Mady –

+0

Lo hice ayer, mientras revisaba nuevamente el código ... pero gracias –

Cuestiones relacionadas