2011-11-04 24 views
6

Deseo dibujar una línea curva hasta que haga una rotación completa y se una para formar un círculo completo, solo el contorno del círculo, no rellenado. Esto tiene que ser animado durante varios segundos.iPhone: Dibujando una línea curva hasta que se convierta en una animación circular

¿Alguien puede indicarme la dirección correcta? Ya le pedí un similar question a esto, pero lo redacté incorrectamente, por lo que a todos les costaba entender lo que quería decir y, por lo tanto, se perdió en el mar de preguntas.

Muchas Gracias por cualquier ayuda

[editar]

estoy actualmente subclasificar UIView y drawRect primordial. Encontré código para dibujar un círculo relleno, pero solo necesito el trazo.

- (void)drawRect:(CGRect)rect { 
// Drawing code 

CGRect allRect = self.bounds; 
CGRect circleRect = CGRectInset(allRect, 2.0f, 2.0f); 

CGContextRef context = UIGraphicsGetCurrentContext(); 

// Draw background 
CGContextSetRGBStrokeColor(context, self.strokeValueRed, self.strokeValueGreen, self.strokeValueBlue, self.strokeValueAlpha); // white 
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 0.1f); // translucent white 
CGContextSetLineWidth(context, self.lineWidth); 
CGContextFillEllipseInRect(context, circleRect); 
CGContextStrokeEllipseInRect(context, circleRect); 

// Draw progress 
CGPoint center = CGPointMake(allRect.size.width/2, allRect.size.height/2); 
CGFloat radius = (allRect.size.width - 4)/2; 
CGFloat startAngle = - ((float)M_PI/2); // 90 degrees 
CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle; 
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1.0f); // white 
CGContextMoveToPoint(context, center.x, center.y); 
CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); 
CGContextClosePath(context); 
CGContextFillPath(context); 
} 

[editar # 2]

he cambiado el código para eliminar todas las referencias de relleno pero ahora es todo lo que no dibujo :(alguna idea?

- (void)drawRect:(CGRect)rect 
{ 
// Drawing code 

CGRect allRect = self.bounds; 
CGContextRef context = UIGraphicsGetCurrentContext(); 

// Draw background 
CGContextSetRGBStrokeColor(context, self.strokeValueRed, self.strokeValueGreen, self.strokeValueBlue, self.strokeValueAlpha); // white 
CGContextSetLineWidth(context, 5); 

// Draw progress 
CGPoint center = CGPointMake(allRect.size.width/2, allRect.size.height/2); 
CGFloat radius = (allRect.size.width - 4)/2; 
CGFloat startAngle = - ((float)M_PI/2); // 90 degrees 
CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle; 
CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); 
CGContextStrokePath(context); 
} 

[editar # 3] Solución

Right Me siento como un idiota derecho! El problema es que los valores de color de trazo no se inicializaron, lo que significa que la línea se estaba dibujando, pero obviamente no pudo verlo!

Respuesta

3

Tome todo lo que dice Fill.

Cambie el CGContextFillPath al final a CGContextStrokePath.

Elimine CGContextMoveToPoint y CGContextClosePath cerca del final. Esos solo delinean los lados rectos de la cuña.

Es posible que tenga que cambiar CGContextMoveToPoint para moverse al punto de inicio del arco en lugar del centro, en lugar de sacarlo.

+0

gracias por su ayuda! – bennythemink

0

Un enfoque muy directo puede ser subclasificar a UIView y hacer que dibuje un arco de longitud variable. A continuación, puede utilizar un temporizador para actualizar periódicamente el ángulo de rotación

+0

hey @Eytan Estaba haciendo eso bien, pero no puedo entender cómo dibujar el trazo solo sin dibujar el círculo lleno. Modifiqué mi publicación anterior para mostrar mi código. – bennythemink

16

Esta es la misma respuesta que le di a su otra pregunta here.

Lo que realmente debe hacer es animar el trazo de un CAShapeLayer donde la ruta es un círculo. Esto se acelerará usando Core Animation y es menos complicado que dibujar parte de un círculo en -drawRect :.

El siguiente código creará una capa circular en el centro de la pantalla y animará el trazo en sentido horario para que parezca que se está dibujando. Por supuesto, puede usar cualquier forma que desee. (Se puede leer en el blog this article Ole Begemanns para aprender más sobre cómo animar el golpe de una capa de forma.)

Nota: que las propiedades Stoke no son las mismas que las propiedades de los bordes de la capa. Para cambiar el ancho del trazo, debe usar "lineWidth" en lugar de "borderWitdh", etc.

// Set up the shape of the circle 
int radius = 100; 
CAShapeLayer *circle = [CAShapeLayer layer]; 
// Make a circular shape 
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) 
             cornerRadius:radius].CGPath; 
// Center the shape in self.view 
circle.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius, 
           CGRectGetMidY(self.view.frame)-radius); 

// Configure the apperence of the circle 
circle.fillColor = [UIColor clearColor].CGColor; 
circle.strokeColor = [UIColor blackColor].CGColor; 
circle.lineWidth = 5; 

// Add to parent layer 
[self.view.layer addSublayer:circle]; 

// Configure animation 
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; 
drawAnimation.duration   = 10.0; // "animate over 10 seconds or so.." 
drawAnimation.repeatCount   = 1.0; // Animate only once.. 

// Animate from no part of the stroke being drawn to the entire stroke being drawn 
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; 
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f]; 

// Experiment with timing to get the appearence to look the way you want 
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 

// Add the animation to the circle 
[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"]; 
+1

hola David, gracias por su ayuda. Establecí su solución como la respuesta a mi pregunta anterior. Me alegra ver que alguien entendió mi mala pregunta :) :) – bennythemink

+0

También estaba buscando esto. Funcionó de maravilla ... Gracias David ... –

+0

'removedOnCompletion' debe ser igual a' SÍ' aquí. La propiedad 'strokeEnd' ya es 1.0 por defecto, y no hay necesidad de mantener la animación en la pantalla una vez que esté completa, perderá batería/rendimiento. De lo contrario, la mejor solución aquí! – Drmorgan

Cuestiones relacionadas