Вы находитесь на странице: 1из 32

Desarrollo de Apps para iOS UIView - Dibujar y Animaciones

SWCM 2010-2011 Santiago Pavn (santiago@dit.upm.es)

ver: 110.216
1

UIView

Qu es una UIView?
Clase base de las views usadas para crear un GUI. El GUI se forma como una jerarqua (rbol) de views Propiedades para recorrer el rbol:

La view padre: UIView *superview Views hijas: NSArray *subviews


3

Construir el GUI
La jerarqua de views puede construirse con el Interface Builder Y mediante cdigo
- (id) initWithFrame:(CGRect)aRect; - (void) addSubview:(UIView*)aView; - (void) removeFromSuperview; - (void) insertSubview:(UIView*)aView atIndex:(int)index; - (void) insertSubview:(UIView*)aView belowSubview:(UIView*)otherView; - (void) insertSubview:(UIView*)aView aboveSubview:(UIView*)otherView;

CGRect r = CGRectMake(50,50,120,40); UILabel * t = [[UILabel alloc] initWithFrame:r]; [window addSubview:t]; [t release];

El contenido de la View
La view dene un rea rectangular en el que se puede dibujar. Si el contenido sobrepasa el rectngulo, se puede pintar o no (clipToBounds). Se puede controlar su transparencia (alpha). La view entera se puede ocultar (hidden). Se puede escalar el contenido, aplicar transformaciones anes, etc.

Ver la documentacin

Eventos
Podemos gestionar los eventos que ocurren en ella. Se puede congurar para:

ignorar los eventos del usuario. decidir si soportar multi-touch. establecer reconocedores de gestos. bloquear el envio de eventos a otras views. etc.
7

Gestin de Memoria
Al aadir una view a la jerarqua se retiene. y el sacarla de la jerarqua se llama a release.

- Cuidado que el contador de retenciones podra


llegar a cero en este momento. Podemos evitarlo llamando antes a retain

IBOutlet
Si una view es un IBOutlet:

La variable de instancia que la apunta la retiene @property (retain) IBOutlet UILabel * l; Paraliberarla, llamamos a release y apuntamos a nil. self.l = nil; Ejemplo: las UIViewController sin memoria lo hacen en viewDidUnload.

Y sobreescribimos dealloc para llamar a release. - (void) dealloc { [l release]; [super dealloc]; }

Coordenadas

10

Algunas Funciones y Estructuras CG


CGPoint - Un punto situado en (x,y) CGSize - Dimensin: width y height CGRect - Rectngulo con origen (x,y) y tamao (width,heigth) Mtodos para crear estas estructuras: CGPoint p = CGPointMake(x,y); CGSize s = CGSizeMake(w,h); CGRect r = CGRectMake(x,y,w,h);
11

Coordenadas
Origen arriba a la izquierda Las unidades son puntos, no pixeles. - Ajuste de resolucin es automtico. Propiedades: - CGRect bounds El origen y tamao de la view en su sistema de coordenadas - CGPoint center El centro de la view en el sistema de coordenadas de la view padre. - CGRect frame Rectngulo que contiene a la view en el sistema de coordenadas de su view padre (puede estar girada)

12

(90,25)

160
10 0

160

(170,105)

12 5
view padre

View hija: bounds = ((0,0),(100,125)) frame = (90,25),(160,160)) center = (170,105)


13

ew vi hi ja

UIView: Dibujar

14

Alternativas para Dibujar


Podemos usar:

- Quartz 2D
es parte del framework Core Graphics

- OpenGL ES
Slo veremos Quartz 2D.
15

Dibujar con Quartz 2D


Se hace usando estructuras y funciones C - Pero UIKits nos proporciona algunos envoltorios tiles CGColor c = [UIColor redColor].CGColor; Para dibujar slo hay que redenir el mtodo: -(void)drawRect:(CGRect)rect;

Incluyendo en l sentencias de pintado.

El pintado perezoso - Nunca llamaremos directamente a drawRect - Cuando haya que refrescar, llamaremos a: -(void)setNeedsDisplay;

Y el sistema llamar a drawRect cuando le venga bien.

16

Temas a Tratar
contexto grco transformaciones paths colores fonts operaciones de pintado texto imgenes
17

Contexto Grco
El pintado se hace usando un contexto grco. Se obtiene usando el mtodo:
(CGContextRef)UIGraphicsGetCurrentContext();

- Slo vlido para la actual llamada a drawRect. - no cachear


Independiza del elemento sobre el que se pinta - pantalla, imagen, impresora,
18

Push y Pop del Contexto Grco


Si se realizan modicaciones al estado del contexto grco, pero no se quiere perder el estado actual:

- puede guardarse el estado actual del contexto grco con:


UIGraphicsPushContext(contexto);

- realizar las modicaciones que se deseen en el contexto grco - y recuperar el estado inicial con:
UIGraphicsPopContext(); Ejemplo de uso: - drawRect invoca un mtodo auxiliar que cambia el estado del contexto para hacer ciertos dibujos. - Este mtodo hace un push al principio y un pop al nal para que los cambios del estado sean locales a l.

19

- (void) drawAxis { ! CGContextRef context = UIGraphicsGetCurrentContext(); // Guardar el contexto actual UIGraphicsPushContext(context); // Realizo cambios en el estado del contexto CGContextSetLineWidth(context, 1); CGContextSetStrokeColorWithColor(context,[UIColor redColor].CGColor); . . . // Recupero el contexto inicial UIGraphicsPopContext(); } . . . - (void)drawRect:(CGRect)rect { [self drawAxis]; [self drawObject]; }

20

Dibujar una L Morada


CGContextRef context = UIGraphicsGetCurrentContext(); CGContextBeginPath(context); CGContextSetLineWidth(context, 3); CGContextSetStrokeColorWithColor(context, [UIColor magentaColor].CGColor); CGContextMoveToPoint(context, 10, 10); CGContextAddLineToPoint(context, 10, 20); CGContextAddLineToPoint(context, 20, 20); CGContextDrawPath(context, kCGPathStroke);

21

UIKits Envoltorios
[[UIColor blueColor] set];

UIFont *font1 = [UIFont systemFontOfSize:14]; UIFont *font2 = [UIFont fontWithName:@"Helvetica" size:24.0];

UIRectFill(rect); UIRectFrame(rect);

22

Dibujar Texto
NSString *text = @hola; CGPoint pos = CGPointMake(10,10); UIFont *font = [UIFont systemFontOfSize:14];

[text drawAtPoint:pos withFont:font];

Es mejor usar un objeto UILabel.

23

Dibujar Imgenes
UIImage *img = [UIImage imageNamed:@"fondo.png"];

[img drawAtPoint:punto]; [img drawAtRect:rect];

Es mejor usar un objeto UIImageView.

24

UIView: Animaciones

25

Aminaciones
UIView soporta animaciones al cambiar el valor de algunas propiedades: - frame, transform, alpha, hidden, La animacin se dene usando un mtodo de clase y bloques. - El mtodo de clase tiene parmetros para ajustar la animacin: retrasos, duracin, curva de velocidad, ... - El bloque contiene el cdigo que cambia el valor de las propiedades de la UIView. - Puede existir un Completion Block que se ejecuta al terminar la animacin. Aunque la animacin no haya terminado, el cambio en los valores de las propiedades es instantneo.

26

+ (void)animateWithDuration:(NSTimeInterval) animations:(void (^)(void)) + (void)animateWithDuration:(NSTimeInterval) animations:(void (^)(void)) completion:(void (^)(BOOL finished)) + (void)animateWithDuration:(NSTimeInterval) delay:(NSTimeInterval) options:(UIViewAnimationOptions) animations:(void (^)(void)) completion:(void (^)(BOOL finished))

27

Ejemplo
@interface AnimacionViewController : UIViewController { IBOutlet UILabel *label; } @property (retain) UILabel *label; -(IBAction) anima; @end

28

- (IBAction) anima { ! static int pos = 100; ! pos = 300-pos; ! CGPoint p = CGPointMake(pos, pos); ! [UIView animateWithDuration:1 animations:^{label.center = p;}]; }

29

Transiciones
Tambin se pueden animar los cambios en la jerarqua de views, y los cambios de visibilidad. + (void)transitionFromView:(UIView *) toView:(UIView *) duration:(NSTimeInterval) options:(UIViewAnimationOptions) completion:(void (^)(BOOL finished)) + (void)transitionWithView:(UIView *) duration:(NSTimeInterval) options:(UIViewAnimationOptions) animations:(void (^)(void)) completion:(void (^)(BOOL finished))

30

Otra forma

Las animaciones y trasiciones tambin pueden hacerse sin usar bloques Usando slo mtodos de clase

31

@implementation AnimacionViewController @synthesize label; -(IBAction) anima { static int pos = 100; [UIView beginAnimations:@payapaca context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationDuration:4]; pos = 300-pos; label.center = CGPointMake(pos, pos); [UIView commitAnimations]; } . . . @end

32

Вам также может понравиться