2012-07-21 15 views
5

Estoy tratando de construir un círculo de animación que se dibuja en sentido horario hasta que se convierte en círculo completo como se ilustra en iPhone Core Animation - Drawing a CircleCALayer como subcapa no visible

problema es que CALayer objeto no se añade o construir. Probé y vi que no está accediendo a mis métodos drawInContext:CGContextRef y animatingArc.

lo que hasta ahora he hecho es:

En AnimateArc.h

@interface AnimateArc : CALayer { 

CAShapeLayer *circle; 
} 

-(void) animatingArc; 

@end 

En AnimateArc.m

-(void) drawInContext:(CGContextRef)ctx 
{ 
CGFloat radius = 50.0; 
circle = [CAShapeLayer layer]; 

//make a circular shape 
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0.0, 0.0, 2 * radius, 2 * radius) cornerRadius:radius].CGPath; 

    CGPoint centerPoint = CGPointMake(CGRectGetWidth(self.bounds)/2, CGRectGetHeight(self.bounds)/2);  

//center the shape in self.view 
circle.position = centerPoint; 

//configure appearence of circle 
circle.fillColor = [UIColor clearColor].CGColor; 
circle.strokeColor = [UIColor blackColor].CGColor; 
circle.lineWidth = 5;           

/*CGPointMake((self.contentsCenter.size.width), (self.contentsCenter.size.height));*/ 

//path the circle 
CGContextAddArc(ctx, centerPoint.x, centerPoint.y, radius, 0.0, 2 * M_PI, 0); 
CGContextClosePath(ctx); 

//fill it 
CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor); 
CGContextFillPath(ctx); } 

//////// ////////////////////////////////////////////////// /////////////

-(void) animatingArc 
{ 
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"arcEnd"]; 
anim.duration = 20.0; //animate over 20 seconds 
anim.repeatCount = 1.0; //animate only once 
anim.removedOnCompletion = NO; //Reamin there after completion 

//animate from start to end 
anim.fromValue = [NSNumber numberWithFloat:50.0f]; 
anim.toValue = [NSNumber numberWithFloat:150.0f]; 

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

//add animation to circle 
[circle addAnimation:anim forKey:@"animatingArc"]; 
} 

/////////////////////

//needed since key not part of animatable properties 
+(BOOL) needsDisplayForKey:(NSString *)key 
{ 
if([key isEqualToString:@"arcEnd"]) 
    return YES; 
else 
    return [super needsDisplayForKey:key]; 

} 

//ensure custom properties copied to presentation layer 
-(id) initWithLayer:(id)layer 
{ 
if((self = [super initWithLayer:layer])) 
{ 
    if ([layer isKindOfClass:[AnimateArc class]]) 
    { 
     AnimateArc *other = (AnimateArc *) layer; 
     [other setNeedsDisplay]; 
    } 
} 
return self; } 

Y, finalmente, en mi viewController,

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
[self.view.layer addSublayer:AnimateArcObject]; 
[AnimateArcObject animatingArc]; 
} 

Apología de mala formato .... ¿Por favor alguien puede decirme qué estoy haciendo mal? También tengo dudas de que mi código pueda bloquearse en cualquier lugar después de acceder a esas dos funciones, ya que soy un novato en Core Animation y no tengo ni idea de que estoy en la buena dirección o no.

Cualquier ayuda será apreciada. Gracias.

Respuesta

0

Después de una pequeña búsqueda, pensé que iba en la dirección equivocada. Así que borré este archivo AnimateArc y agregué uno nuevo que es heredando de UIViewController.

Luego en el método viewDidLoad, escribí el código de this link para crear un círculo y animaciones usando la ruta.

En Controlador de vista principal, He añadido AnimatedArc ViewController's subview. Ahora está funcionando perfectamente :)

16

Desde mi experiencia dolorosa con CoreAnimation, debe siempre establecer la propiedad bounds de cualquier CALayer usted instancia.

Por lo tanto, estás capa no se muestra porque se echa en falta algo como:

layer.bounds = CGRectMake(0, 0, width, height);

debe colocar esto tan pronto como se ejemplariza la capa y hacer un hábito de hacerlo, para que no te vuelvas a caer en ella.

En cuanto a su bloqueo de código, lo siento. Está muy distribuido y no estoy seguro de cómo está unido, así que no puedo ayudarte allí.

+0

Gracias por su respuesta.Pero establecer límites todavía no resolvió mi problema :( – NightFury

+0

Me ayudó, pero no lo resolvió completamente. La capa ahora está dibujando en la pantalla, pero ligeramente desplazada de la vista/capa principal incluso cuando establecí los límites de la capa en el marco de vistas principal. Me falta algo fundamental, parece. – tracicot

+2

@tracicot usted __must__ establece los límites de la capa al origen '(0, 0)'. Luego, use la propiedad del centro para cambiar la posición. También puede establecer el marco de capas directamente para controlar la posición. – Mazyod