2010-07-28 10 views
8

En uno de mis métodos tengo este código:UIBezierPath en vista

-(void)myMethod { 
    UIBezierPath *circle = [UIBezierPath 
         bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)]; 
} 

¿Cómo consigo que se muestre en la vista?

Intenté addSubview pero me dio un incompatible type error porque está esperando un UIView.

Estoy seguro de que esto debe ser simple.

Gracias

Respuesta

18

Puede dibujar utilizando uno o fillstroke métodos, por ejemplo en la aplicación de vista personalizada drawInRect::

- (void)drawRect:(CGRect)rect { 
    // Drawing code 
    UIBezierPath *circle = [UIBezierPath 
        bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)]; 
    [circle fill]; 
} 
+0

yo probamos este, pero no pasa nada. ¿Cómo obtengo el dibujo en mi vista personalizada? – joec

+1

Crear la subclase UIView e implementar el método drawRect allí, funciona para mí al menos – Vladimir

+1

Esto es antiguo, pero en caso de que ayude a otra persona: Olvidé especificar que mi vista en Interface Builder es del tipo "MyView" (identidad de clase) – Mirkules

2

El dibujo es la provisión exclusiva de puntos de vista. Cree una vista personalizada, proporciónela e implemente el método drawRect: de la vista para rellenar y/o trazar la ruta.

+0

Así que hice una vista personalizada, luego hice esto en mi otro controlador de vista 'JogShuttle * js = [[JogShuttle alloc] initWithFrame: CGRectMake (...)]; [self.view addSubView: js]; 'pero no se dibuja nada en la vista? – joec

+0

¿Podría publicar un código más? ¿Qué marco configuras para tu vista js? Compruebe si su camino bezier está dentro de los límites de la vista? – Vladimir

+0

lo resolvió - gracias. – joec

27

Solo tengo que añadir que no tiene que necesariamente dibujar esto en el método "draw_rect:" de UIView. Puede dibujarlo en cualquier lugar que desee siempre que lo haga dentro de un contexto de imagen UIGraphics. Hago esto todo el tiempo cuando no quiero crear una subclase de UIView. Aquí hay un ejemplo de trabajo:

UIBezierPath *circle = [UIBezierPath 
         bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)]; 

//you have to account for the x and y values of your UIBezierPath rect 
//add the x to the width (75 + 200) 
//add the y to the height (100 + 200) 
UIGraphicsBeginImageContext(CGSizeMake(275, 300)); 

//this gets the graphic context 
CGContextRef context = UIGraphicsGetCurrentContext(); 

//you can stroke and/or fill 
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor); 
[circle fill]; 
[circle stroke]; 

//now get the image from the context 
UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage]; 

Ahora solo agregue el UIImageView como subvista.

Además, puede usar esto también para otros dibujos. Una vez más, después de un poco de configuración, funciona igual que el método drawRect :.

//this is an arbitrary size for example 
CGSize aSize = CGSizeMake(50.f, 50.f); 

//this can take any CGSize 
//it works like the frame.size would in the drawRect: method 
//in the way that it represents the context's size 
UIGraphicsBeginImageContext(aSize); 

//this gets the graphic context 
CGContextRef context = UIGraphicsGetCurrentContext(); 

//you can do drawing just like you would in the drawRect: method 
//I am drawing a square just for an example to show you that you can do any sort of drawing in here 
CGContextMoveToPoint(context, 0.f, 0.f); 
CGContextAddLineToPoint(context, aSize.width, 0.f); 
CGContextAddLineToPoint(context, aSize.width, aSize.height); 
CGContextAddLineToPoint(context, 0.f, aSize.height); 
CGContextClosePath(context); 

//you can stroke and/or fill 
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor); 
CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor); 
CGContextDrawPath(context, kCGPathFillStroke); 

//now get the image from the context 
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext(); 

UIGraphicsEndImageContext(); 

UIImageView *squareImageView = [[UIImageView alloc]initWithImage:squareImage]; 

Editar: Una cosa debo añadir es que para cualquier dibujo moderna de este tipo, debe estar intercambiando

UIGraphicsBeginImageContext(size); 

para

UIGraphicsBeginImageContextWithOptions(size, opaque, scale); 

Para ello se utilizará sus gráficos correctamente para pantallas retina y no retina.

FYI, UIGraphicsBeginImageContext(size) es equivalente a UIGraphicsBeginImageContextWithOptions(size, FALSE, 1.f) que está bien para ninguna pantalla retina que pueda tener cierta transparencia.

Sin embargo, si no necesita transparencia, está más optimizado para pasar TRUE para el argumento opaco.

La forma más segura y recomendada de dibujar es pasar [[UIScreen mainScreen]scale] como argumento de la escala.

Así, por ejemplo, la (s) anterior, se utiliza en su lugar:

UIGraphicsBeginImageContextWithOptions(aSize, FALSE, [[UIScreen mainScreen] scale]); 

Para obtener más información, echa un vistazo a Apple's docs.

+0

explicación simple, concisa y útil; +1. –

10

También puede agregar UIBezierPath a UIView sin crear subclases mediante CAShapeLayer.

Por ejemplo, para añadir su ruta como una línea blanca 3pt centrada en un UIView:

UIBezierPath *mybezierpath = [UIBezierPath 
        bezierPathWithOvalInRect:CGRectMake(0, 0, 100, 100)]; 

CAShapeLayer *lines = [CAShapeLayer layer]; 
lines.path = mybezierpath.CGPath; 
lines.bounds = CGPathGetBoundingBox(lines.path); 
lines.strokeColor = [UIColor whiteColor].CGColor; 
lines.fillColor = [UIColor clearColor].CGColor; /*if you just want lines*/ 
lines.lineWidth = 3; 
lines.position = CGPointMake(self.myview.frame.size.width/2.0, self.myview.frame.size.height/2.0); 
lines.anchorPoint = CGPointMake(.5, .5); 

[self.myview.layer addSublayer:lines]; 
1

En Swift 2.0:

let path = UIBezierPath() 

let p1 = CGPointMake(0,self.view.frame.height/2) 
let p3 = CGPointMake(self.view.frame.width,self.view.frame.height/2) 

path.moveToPoint(p1) 
path.addQuadCurveToPoint(p3, controlPoint: CGPoint(x: self.view.frame.width/2, y: 0)) 

let line = CAShapeLayer() 
line.path = path.CGPath; 
line.strokeColor = UIColor.blackColor().CGColor 
line.fillColor = UIColor.redColor().CGColor 
view.layer.addSublayer(line) 
Cuestiones relacionadas