2011-03-25 8 views
11

¿Cómo puedo dibujar una línea usando CGPath?dibuje una línea usando CGPath

+1

¿Cómo es difícil decir lo que se le está pidiendo aquí? ¿Qué otra interpretación de la pregunta puede existir que la de que el autor de la pregunta quiso saber cómo dibujar un CGPath que representa una línea? – moonman239

+0

Hay muchas formas de trazar una línea. Core Graphics, Quartz, OpenGL, SpriteKit, GLKit, SceneKit, GL Shaders - solo por nombrar algunos. Tendríamos que adivinar la intención/marco preferido del PO. – LearnCocos2D

+1

¿No es seguro suponer Core Graphics, ya que hace referencia a CGPath? –

Respuesta

8

theView.h

#import <UIKit/UIKit.h> 

@interface theView : UIView { 
} 

@end 

theView.m

#import "theView.h" 

@implementation theView 

-(void)drawRect:(CGRect)rect { 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextSetLineWidth(context, 2.0); 
    CGContextMoveToPoint(context,0,0); 
    CGContextAddLineToPoint(context,20,20); 
    CGContextStrokePath(context); 
} 

@end 

Crear los archivos mencionados anteriormente.
Aplicación basada en la ventana: agregue una nueva UIView y cambie su clase a la Vista.
Aplicación basada en la vista: cambie la clase UIView a View.
Finalmente pulse 'compilar y ejecutar' :)

Resultado: Línea diagonal roja.

+0

¿No deberías también lanzar el camino o algo así? –

+2

No creo que hayas respondido la pregunta. El OP quiere saber cómo crear un CGPath que represente una línea y dibujar ese CGPath. – moonman239

27

Como realmente no especificó más que cómo dibujar una línea con una ruta, le daré un ejemplo.

Dibujar una línea diagonal entre la esquina superior izquierda y la inferior derecha (en iOS) con una ruta en drawRect de un UIView:

- (void)drawRect:(CGRect)rect { 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathMoveToPoint(path, NULL, 0, 0); 
    CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect)); 
    CGPathCloseSubpath(path); 
    CGContextAddPath(ctx, path); 
    CGContextSetStrokeColorWithColor(ctx,[UIColor whiteColor].CGColor); 
    CGContextStrokePath(ctx); 
    CGPathRelease(path); 
} 
Cuestiones relacionadas