Escolar Documentos
Profissional Documentos
Cultura Documentos
#
INSTITUTO DE ARTES INTERATIVAS
!"!#
INSTITUTO DE ARTES INTERATIVAS
!"!#
INSTITUTO DE ARTES INTERATIVAS
iPhone SDK
Mdulo 3
!"!#
INSTITUTO DE ARTES INTERATIVAS
XML
Leitura de XML com NSXMLParser
O que so arquivos XML? !"!#
INSTITUTO DE ARTES INTERATIVAS
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName ...
ENCONTREI TEXTO
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName ...
Prtica !"!#
INSTITUTO DE ARTES INTERATIVAS
<stocks>
<data>
<date>13/09/2009</date>
<max>29.99</max>
<min>22.80</min>
<open>25.4</open>
<close>23.9</close>
.xml </data>
<data>
<date>14/09/2009</date>
<max>32.99</max>
<min>21.80</min>
<open>26.4</open>
<close>27.9</close>
</data>
</stocks>
Criando o projeto !"!#
INSTITUTO DE ARTES INTERATIVAS
D a ele o nome
de XMLParser
Adicionando a classe XMLParser !"!#
INSTITUTO DE ARTES INTERATIVAS
@end
[data release];
Definindo o delegate !"!#
INSTITUTO DE ARTES INTERATIVAS
XMLParser.m
[nsparser setDelegate:self];
!!
DIZ PARA O NOSSO OBJETO PARSER QUE ESTA CLASSE O DELEGATE, OU
SEJA, QUEM TER DE TRATAR AS MENSAGENS QUE nsparser GERA
[nsparser parse];
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName attributes:
(NSDictionary *)attributeDict{
ESTE MTODO SER CHAMADO SEMPRE QUE O
PARSER ENCONTRAR UMA TAG ABRINDO!
}
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string{
! NSLog(@"achou texto: %@", string);
}
Nossa classe fica assim: !"!#
INSTITUTO DE ARTES INTERATIVAS
INICIALIZAO
LEITURA DO XML
Testando os mtodos !"!#
INSTITUTO DE ARTES INTERATIVAS
! XMLParser *parser;
}
@end
Testando os mtodos !"!#
INSTITUTO DE ARTES INTERATIVAS
! if ([currentTag isEqualToString:@"data"]) {
! ! currentData = [[NSMutableDictionary alloc] init];
! }else if([currentTag isEqualToString:@"stocks"] == NO){
! ! currentValue = [[NSMutableString alloc] init];
! }
!
} CASO SEJA QUALQUER OUTRA (exceto a raiz stocks),
INICIAMOS currentValue
Armazenando os valores !"!#
INSTITUTO DE ARTES INTERATIVAS
! if ([elementName isEqualToString:@"data"]) {
! ! [values addObject:currentData];
-(NSArray*) getXMLValues;
@end
-(NSArray*) getXMLValues{
! return [NSArray arrayWithArray:values];
}
Recebendo os dados no ViewController !"!#
INSTITUTO DE ARTES INTERATIVAS
@end
[super viewDidLoad];
! parser = [[XMLParser alloc] init];
! values = [[parser getXMLValues] retain];
TEMOS QUE RETER ESTA VARIVEL, ASSIM PODEREMOS UTILIZ-LA EM TODA NOSSA CLASSE
Configurando o Table View !"!#
INSTITUTO DE ARTES INTERATIVAS
Exerccios
1) Tente criar uma nova view para
mostrar em detalhes o dia, com os
valores de abertura, fechamento,
mximo e mnimo. Empilhe esta view
quando uma das clulas for selecionada
SQLITE
Banco de dados SQL Built-in
Porque usar SQLITE? !"!#
INSTITUTO DE ARTES INTERATIVAS
D a ele o nome
de SQLiteAgenda
Pr-requisitos !"!#
INSTITUTO DE ARTES INTERATIVAS
start_script
@end
Criar um objeto para os dados !"!#
INSTITUTO DE ARTES INTERATIVAS
-(void)dealloc {
[name release];
[phone release];
[email release];
[city release];
}
@end
AppDelegate - gerencia o banco !"!#
INSTITUTO DE ARTES INTERATIVAS
-(void)iniciarBancoDeDados;
-(void)atualizarComDadosDoBanco;
-(NSMutableArray*)arrayFiltradoComQuery:(NSString*)query;
-(void)adicionarItemAoBanco:(Contato*)oContato;
@end
Banco - copiar para Documents !"!#
INSTITUTO DE ARTES INTERATIVAS
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
[self iniciarBancoDeDados];
[self atualizarComDadosDoBanco];
return YES;
}
-(void)iniciarBancoDeDados {
contatosArray = [[NSMutableArray alloc] init];
databasePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/
Agenda.sql"] retain];
-(void)atualizarComDadosDoBanco {
// Inicializo o objeto do banco
! sqlite3* database;
! // Abrir o banco
! if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
! ! sqlite3_stmt *compiledStatement;
! ! // Se tudo ok, vamos varrer o banco
! ! if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement,
NULL) == SQLITE_OK) { .......
Atualizando o array - continua !"!#
INSTITUTO DE ARTES INTERATIVAS
}
Query no banco !"!#
INSTITUTO DE ARTES INTERATIVAS
! // Abrir o banco
! if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
! ! // Criar a chamada SQL e verificar se esta valida
! ! const char *sqlStatement = [query
cStringUsingEncoding:NSUTF8StringEncoding];
! ! sqlite3_stmt *compiledStatement;
! ! if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)
== SQLITE_OK) {
Query no banco - continua !"!#
INSTITUTO DE ARTES INTERATIVAS
//Retornar resultado
return arrayFiltrado;
Adicionar item no banco !"!#
INSTITUTO DE ARTES INTERATIVAS
}
Criando a tela de cadastro !"!#
INSTITUTO DE ARTES INTERATIVAS
ESCOLHA VIEWCONTROLER
Configure a tela
NovoContatoViewController.xib, crie e
conecte os IBOutlets e declare que essa
classe vai implementar os mtodos do text
field.
NovoContatoViewController.h
#import <UIKit/UIKit.h>
#import "SQLiteAgendaAppDelegate.h"
#import "Contato.h"
@interface NovoContatoViewController :
UIViewController <UITextFieldDelegate>{
-(void)salvarContato;
NovoContatoViewController.xib
Boto de adicionar Contato !"!#
INSTITUTO DE ARTES INTERATIVAS
@implementation NovoContatoViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Contatos";
[nomeField becomeFirstResponder];
}
Mtodo de salvar !"!#
INSTITUTO DE ARTES INTERATIVAS
-(void)salvarContato {
[appDelegate adicionarItemAoBanco:novoContato];
[novoContato release];
}
Administrando o teclado !"!#
INSTITUTO DE ARTES INTERATIVAS
NovoContatoViewController.m
if (textField == nomeField)
[phoneField becomeFirstResponder];
if (textField == phoneField)
[emailField becomeFirstResponder];
if (textField == cidadeField)
[nomeField becomeFirstResponder];
}
Exibindo os dados !"!#
INSTITUTO DE ARTES INTERATIVAS
UISegmentedControl* filtroSegment;
NSMutableArray* arrayTabela;
}
-(void)filtrarConteudo:(UISegmentedControl*)segmento;
@end
Editando a lista !"!#
INSTITUTO DE ARTES INTERATIVAS
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self filtrarConteudo:filtroSegment];
}
Filtrar o contedo !"!#
INSTITUTO DE ARTES INTERATIVAS
[arrayTabela removeAllObjects];
if (segmento.selectedSegmentIndex == 0) {
[arrayTabela addObjectsFromArray:appDelegate.contatosArray];
}
else {
NSMutableArray* filteredArray = [appDelegate arrayFiltradoComQuery:@"SELECT * FROM
Friends WHERE email <> ''"];
[arrayTabela addObjectsFromArray:filteredArray];
}
[self.tableView reloadData];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self filtrarConteudo:filtroSegment];
}
Montar tabela para exibir contatos !"!#
INSTITUTO DE ARTES INTERATIVAS
cell.textLabel.text = oContato.name;
cell.detailTextLabel.text = oContato.email;
return cell;
}
Removendo contatos !"!#
INSTITUTO DE ARTES INTERATIVAS
if (editingStyle == UITableViewCellEditingStyleDelete) {
Core Graphics
API de grficos 2D para iPhone
Porque utilizar o Core Graphics? !"!#
INSTITUTO DE ARTES INTERATIVAS
x
Ordem de desenho !"!#
INSTITUTO DE ARTES INTERATIVAS
1 . SELECIONE A VIEW
CGRelogioViewController.xib
Este cdigo captura o contexto, com esta varivel agora vamos poder
informar ao Core Graphics quem o destino dos comandos de desenho.
Desenhando um quadraro !"!#
INSTITUTO DE ARTES INTERATIVAS
10
80
SO EXATAMENTE AS MEDIDAS
QUE DEFINIMOS NO CGRECT!
Alinhamento !"!#
INSTITUTO DE ARTES INTERATIVAS
- (void)drawRect:(CGRect)rect {
// Drawing code
! CGContextRef cgref = UIGraphicsGetCurrentContext();
!
! CGContextSetRGBFillColor(cgref, 0.5, 0.5, 0.9, 1);
! CGContextFillRect(cgref, CGRectMake(
rect.size.width/2,
rect.size.height/2,
h/2
80, 80));
}
A VARIVEL rect ARMAZENA A REA DA VIEW DISPONVEL PARA
DESENHO. QUANDO USAMOS size.width/2 ESTAMOS
CONSIDERANDO A METADE DA LARGURA DA VIEW. O MESMO VALE
PARA size.height/2. NOTE QUE MESMO ASSIM AINDA NO
CONSEGUIMOS CENTRALIZ-LO!
Desenhando o relgio !"!#
INSTITUTO DE ARTES INTERATIVAS
UIViewRelogio.m
}
SUBSTITUA RECT POR ELLIPSE!
Desenhando o relgio, parte 2 !"!#
INSTITUTO DE ARTES INTERATIVAS
}
REPARE QUE A ORDEM AQUI FAZ DIFERENA!
Desenhando o relgio, parte 2 !"!#
INSTITUTO DE ARTES INTERATIVAS
sin e cos
sin =
cos =
Desenhando o ponteiro com sin e cos !"!#
INSTITUTO DE ARTES INTERATIVAS
@end
UIViewRelogio.m
! ! ! ! ! ! ! ! ! ! ! ! rect.size.width/2 - 35,
! ! ! ! ! ! ! ! ! ! ! ! rect.size.height/2 - 35,
! ! ! ! ! ! ! ! ! ! ! ! 70, 70));
SIN ESPERA UM ANGULO EM RADIANOS, QUE
! VAI DE 0 AT 2*PI, AQUI DIVIDIMOS ESTE VALOR
! contador += (2*M_PI)/60; POR 60, OU SEJA, 60 MUDANAS DE POSIO
! AT COMPLETAR UMA VOLTA.
! //inicia o path
! CGContextBeginPath(cgref);
Desenhando o ponteiro com sin e cos !"!#
INSTITUTO DE ARTES INTERATIVAS
! // pinta o patg
! CGContextSetRGBStrokeColor(cgref, 1.0, 0.0, 0.0, 1);
! CGContextStrokePath(cgref);
!
! contador += (2*M_PI)/60;
!
! [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(setNeedsDisplay)
userInfo:nil repeats:NO];
!
}
DESTA MANEIRA NOSSA FUNCO QUE DESENHA O PONTEIRO SER
CHAMADA A CADA SEGUNDO : )
Exerccios !"!#
INSTITUTO DE ARTES INTERATIVAS
Exerccios
1) Faa tambm o ponteiro das horase
dos minutos!
GameKit
Conectividade sem fio utilizando Gamekit
Introduo !"!#
INSTITUTO DE ARTES INTERATIVAS
2. POSSO CONECTAR?
1. PEA PARA 3. QUER CONECTAR
CONECTAR COM A?
COM B
A
B
6. USURIO B
CONECTADO! 4. RESPONDA SIM
5. SIM!
Criando o projeto !"!#
INSTITUTO DE ARTES INTERATIVAS
ControleRede.h
#import <Foundation/Foundation.h>
#import <GameKit/GameKit.h>
! GKSession *chatSession;
@end
Iniciando a sesso na rede. !"!#
INSTITUTO DE ARTES INTERATIVAS
@implementation ControleRede
sessionMode:GKSessionModePeer];
! !
! ! TEMOS 3 MODOS DE REDE : CLIENT,
! } SERVER E PEER. PARA O CHAT, VAMOS
UTILIZAR O MODO PEER!
! return self;
}
Configurando-se como delegate. !"!#
INSTITUTO DE ARTES INTERATIVAS
! ! ! displayName:[UIDevice currentDevice].name
! ! ! sessionMode:GKSessionModePeer];
! !
! ! chatSession.delegate = self;
! }
! return self;
}
}
PARA TRANSFORMAR O peerID EM UM NOME,
UTILIZAMOS O MTODO displayNameForPeer
ControleRede.m
! ! chatSession.delegate = self;
! ! chatSession.available = YES; ATIVAMOS A REDE DESTA MANEIRA
! } DENTRO DO MTODO INIT
! return self;
Anlisando os estados !"!#
INSTITUTO DE ARTES INTERATIVAS
GKPublicConstants.h
! GKPeerStateAvailable,
O USURIO NO EST MAIS DISPONVEL
! GKPeerStateUnavailable,
ESTE USURIO ACEITOU A CONEXO E VOC J PODE
! GKPeerStateConnected, TROCAR DADOS COM ELE
ControleRede.m
ControleRede.m
- (void)session:(GKSession *)session
! ! didReceiveConnectionRequestFromPeer:(NSString *)peerID{
!
! [chatSession acceptConnectionFromPeer:peerID error:nil];
!
}
PRIMEIRO O USURIO
FICA DISPONVEL
ACEITA A CONEXO E
EST DISPONVEL PARA
TROCAR DADOS!
Interface do Chat !"!#
INSTITUTO DE ARTES INTERATIVAS
GKChatViewController.h
FAA TAMBM OS IBOutlets E
CONECTE-OS A INTERFACE
@interface GKChatViewController :
UIViewController {
! ControleRede *rede;
! IBOutlet UITextField *uitMensagem;
! IBOutlet UITextView *uitvMensagens;
GKChatViewController.xib }
@end
Preparando o mtodo de enviar. !"!#
INSTITUTO DE ARTES INTERATIVAS
-(void) enviaMensagem:(NSString*)msg;
@end
E a sua implementao:
ControleRede.m
-(void) enviaMensagem:(NSString*)msg{
}
Recebendo dados !"!#
INSTITUTO DE ARTES INTERATIVAS
E a implementao:
ControleRede.m
-(void) enviaMensagem:(NSString*)msg;
Referenciando o delegate !"!#
INSTITUTO DE ARTES INTERATIVAS
-(void) enviaMensagem:(NSString*)msg;
@synthesize delegate;
- (id) init
SINTETIZE-A NO .m
{
! self = [super init];
Atribuindo o delegate !"!#
INSTITUTO DE ARTES INTERATIVAS
ControleRede.m
- (void)viewDidLoad {
[super viewDidLoad];
! rede = [[ControleRede alloc] init]; self SIGNIFICA ESTE OBJETO. SEU
ENDEREO NA APLICAO, QUEM O TEM
! rede.delegate = self;
PODE CHAMAR MTODOS DESTE OBJETO
}
rede
(GKChatViewController) self
(GKSession) chatSession
(ControleRede) rede
ACESSA O OBJETO DO TIPO (id) delegate
(UITextField) uitMensagem
ControleRede QUE
(UITextView) uitvMensagens
INICIAMOS NO NOSSO VIEW
CONTROLLER.
GKChatViewController ControleRede
rede.delegate
(GKChatViewController) self
(GKSession) chatSession
(ControleRede) rede
(id) delegate
CHAMA A PROPRIEDADE (UITextField) uitMensagem
delegate DA NOSSA (UITextView) uitvMensagens
.
VARIVEL rede.
GKChatViewController ControleRede
rede.delegate = self; =
(GKChatViewController) self
(GKSession) chatSession
ATRIBUI O ENDEREO DO (ControleRede) rede
(id) delegate
NOSSO VIEW CONTROLLER A (UITextField) uitMensagem
PROPRIEDADE delegate DO (UITextView) uitvMensagens
OBJETO ControleRede .
CHAMADO rede.
GKChatViewController ControleRede
Utilizando o delegate !"!#
INSTITUTO DE ARTES INTERATIVAS
ControleRede.m
ControleRede.h
#import <Foundation/Foundation.h>
#import <GameKit/GameKit.h>
required INFORMA QUE ESTES
MTODOS ABAIXO TEM DE EXISTIR
OBRIGATORIAMENTE
@protocol ControleRedeDelegate
@required
-(void) recebeMensagem:(NSString*) texto;
@end
ControleRede.h
GKChatViewController.h
#import <UIKit/UIKit.h>
#import "ControleRede.h"
@end
Recebendo o texto !"!#
INSTITUTO DE ARTES INTERATIVAS
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)
Enviando pelo view controller !"!#
INSTITUTO DE ARTES INTERATIVAS
GKChatViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
! rede = [[ControleRede alloc] init];
! rede.delegate = self;
! uitMensagem.delegate = self; PEDIMOS AO CAMPO DE TEXTO QUE NOS INFORME DOS EVENTOS QUE SE
} PASSAR, POR MEIO DO PROTOCOLO UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
! [rede enviaMensagem:uitMensagem.text];
! uitMensagem.text = @""; ENVIAMOS O TEXTO PARA O CONTROLE DE REDE, LIMPAMOS
[uitMensagem resignFirstResponder]; O CAMPO DE TEXT E ESCONDEMOS O TECLADO
return YES;
}
Exerccios !"!#
INSTITUTO DE ARTES INTERATIVAS
NSThread
Processamento paralelo utilizando Threads
Introduo !"!#
INSTITUTO DE ARTES INTERATIVAS
+detachNewThreadSelector:toTarget:withObject:
- initWithTarget:selector:object:
+sleepForTimeInterval:
@end
- (void)viewDidLoad {
[super viewDidLoad];
links = [[NSMutableArray alloc] init];
}
LEMBRE-SE DE RETIRAR AS MARCAES DE COMENTRIO NO MTODO
Adicionando os links ao vetor !"!#
INSTITUTO DE ARTES INTERATIVAS
ThreadGalleryViewController.m
@end
ThreadGalleryViewController.m
! [links addObject:@"http://upload.wikimedia.org/wikipedia/commons/
! [links addObject:@"http://upload.wikimedia.org/wikipedia/commons/
!
}
ThreadGalleryViewController.m
! [links addObject:@"http://upload.wikimedia.org/wikipedia/commons/
! [links addObject:@"http://upload.wikimedia.org/wikipedia/commons/
!
! imagem.image = [self carregaDaInternet:[links objectAtIndex:0]];
!
}
-(void) exibeImagens{
!
! NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
! int contador = 0;
!
! while (1) {
! ! NSString *link = [links objectAtIndex:contador%[links count]];
-(void) exibeImagens{
!
! NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
! int contador = 0;
!
! while (1) {
! ! NSString *link = [links objectAtIndex:contador%[links count]];
! [links addObject:@"http://upload.wikimedia.org/wikipedia/commons/
! [links addObject:@"http://upload.wikimedia.org/wikipedia/commons/
!
! [NSThread detachNewThreadSelector:@selector(exibeImagens)
toTarget:self withObject:nil];
!
}
NO VAMOS MAIS PRECISAR DO TESTE QUE ESTAVA AQUI
-(UIImage*) carregaDaInternet:(NSString*) link{
! NSURL *url = [NSURL URLWithString:link];
Teste o aplicativo !"!#
INSTITUTO DE ARTES INTERATIVAS
POST
Recebendo e enviando dados a Internet via POST
Introduo !"!#
INSTITUTO DE ARTES INTERATIVAS
NSURL
!
NSURLRequest CUIDA DA REQUISIO, ALM DA URL, CRIA UM PACOTE COM
A DESCRIO DO NOSSO PEDIDO, INCLUSIVE AS VARIVEIS!
!!
NSURLConnection
FAZ O TRFEGO DE REDE, ENVIA O PEDIDO, CAPTURA A
RESPOSTA
Server Side !"!#
INSTITUTO DE ARTES INTERATIVAS
INTERNET
iPhone
Flickr
REQUISIO
RESPOSTA
- (void)viewDidLoad {
[super viewDidLoad];
!
! NSURL *url = [NSURL URLWithString:@"http://api.flickr.com/services/rest/"];
FlickrPOSTViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
!
NSURL *url = [NSURL URLWithString:@"http://api.flickr.com/services/rest/"];
}
PODEMOS CONFIGURAR O REQUEST COM OS
VALORES DE HTTPMethod: POST OU GET
Criando o corpo da requisio !"!#
INSTITUTO DE ARTES INTERATIVAS
FlickrPOSTViewController.m
! [body appendString:@"api_sig=53e52931aa2d11deb06aca77b8f43d05"];
!
! NSData *myRequestData = [NSData dataWithBytes:
[body UTF8String] length:[body length]];
FlickrPOSTViewController.m
}
Lidando com os erros !"!#
INSTITUTO DE ARTES INTERATIVAS
FlickrPOSTViewController.m
cancelButtonTitle:@"ok"
otherButtonTitles:nil];
! [alert show];
! [alert release];
}
-(void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data {
!
! NSString *str = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
! NSLog(@"resposta: %@", str);
!
}
VAMOS VER NO CONSOLE QUAL FOI A RESPOSTA
DO SERVIDOR DA API DO Flickr!
Recuperando o link da imagem !"!#
INSTITUTO DE ARTES INTERATIVAS
http://farm{farm-id}.static.ickr.com/{server-id}/{id}_{secret}.jpg
EXEMPLO DE RESPOSTA
http://farm4.static.ickr.com/3374/3411384625_74167a8895.jpg
Exerccios !"!#
INSTITUTO DE ARTES INTERATIVAS
OpenGL
Introduo ao 3D utilizando OpenGL
Introduo !"!#
INSTITUTO DE ARTES INTERATIVAS
A
Note que os pontos A,B e C so
vrtices. De A at B existe uma aresta. A
unio das arestas de AB, BC,CA formam
o tringulo(face) em vermelho
C B
Adquirindo o projeto !"!#
INSTITUTO DE ARTES INTERATIVAS
iai.art.br/escola/iphonesdk3/opengl/projeto.zip
GLViewController.m
@implementation GLViewController
- (void)drawView:(GLView*)view{
!
! static const Vertex3D vertices[]= {
! ! {-13, 20, 0}, // 0
! ! { 13, 20, 0}, // 1!!
NOSSOS VRTICES
! ! {-13, 0, 0}, // 2
! };
!
! static const GLubyte elementFaces[] = {
! ! 0,1,2
! };
NOSSAS FACES
!
! glLoadIdentity();!
! glTranslatef(0, 0, -35); AJUSTAMOS A VISO
!
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 3,
GL_UNSIGNED_BYTE, elementFaces);
!
}
DESENHAMOS OS PONTOS
Adicionando cor !"!#
INSTITUTO DE ARTES INTERATIVAS
GLViewController.m
! ! { 13, 20, 0}, // 1!
! ! {-13, 0, 0}, // 2
! };
!
! static const Color3D colors[] = {
! ! {0.0, 1.0, 0.0, 1.0},
! ! {0.0, 1.0, 0.0, 1.0},
! ! {0.0, 0.0, 1.0, 1.0}, UMA COR PARA CADA VRTICE
! };
!
! static const GLubyte elementFaces[] = {
! ! 0,1,2
! };
! HABILITAMOS O VETOR DE CORES
! glLoadIdentity();!
! glTranslatef(0, 0, -35);
!
! glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
! glEnableClientState(GL_VERTEX_ARRAY);
! glEnableClientState(GL_COLOR_ARRAY); ADICIONAMOS O COLOR POINTER
! glVertexPointer(3, GL_FLOAT, 0, vertices);
! glColorPointer(4, GL_FLOAT, 0, colors);
! glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_BYTE, elementFaces);
! glDisable(GL_VERTEX_ARRAY);
! glDisable(GL_COLOR_ARRAY); VOLTAMOS AO ESTADO NATURAL
}
Algumas consideraes !"!#
INSTITUTO DE ARTES INTERATIVAS
GLViewController.m
! static const Vertex3D vertices[]= {
! ! {-13, 20, 0}, // 0
! ! { 13, 20, 0}, // 1!!
! ! {-13, 0, 0}, // 2 VERTCES
! ! { 13, 0, 0}, // 0
! };
!
GLViewController.m
- (void)drawView:(GLView*)view{
!
! delta += 4.5;
!
! static const Vertex3D vertices[]= {
! ! {-13, 20, 0}, // 0
! ! { 13, 20, 0}, // 1!!
! ! {-13, 0, 0}, // 2
Aplicando a variao !"!#
INSTITUTO DE ARTES INTERATIVAS
GLViewController.m
! ! 0,1,2,
! ! 1,2,3
! };
!
! glLoadIdentity();
! glTranslatef(0, 0, -35);
! glRotatef(delta, 0.0, 1.0, 0.0);
!
! glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Exerccios
1) Adicione novos pontos, faces e crie
um cubo!
Instruments
Gerenciamento de memria
Introduo !"!#
INSTITUTO DE ARTES INTERATIVAS
ExemploLeakViewController.m
#import <UIKit/UIKit.h>
@interface ExemploLeakViewController :
UIViewController {
! IBOutlet UITextView *texto;
}
-(IBAction) criaLeak;
@end
Implementao do IBAction !"!#
INSTITUTO DE ARTES INTERATIVAS
ExemploLeakViewController.h
-(IBAction) criaLeak{
!
!
! NSMutableString *textoLeak = [NSMutableString string];
!
! for (int i = 0; i < 100 ; i ++) {
! !
! ! NSArray *frases = [[NSArray alloc ] initWithObjects:@"lorem ipsum dolor",
! ! ! ! ! ! @"sit er elit lamet",
! ! ! ! ! ! @"consectetaur cillium adipisicing pecu",
! ! ! ! ! ! @"sed do eiusmod tempor incididunt ut ",
! ! ! ! ! ! @"labore et dolore magna aliqua" ,
! ! ! ! ! ! nil];
! !
! ! [textoLeak appendString:[frases objectAtIndex:arc4random()%[frases
count]]];
! }
! CRIA UMA NSSTRING COM 100 FRASES
! texto.text = textoLeak; ALEATRIAS A PARTIR DO VETOR frases
}
MOSTRA A FRASE NO UITextView
Teste !"!#
INSTITUTO DE ARTES INTERATIVAS
Funciona!
No o suficiente?
Analizando o cdigo !"!#
INSTITUTO DE ARTES INTERATIVAS
Agora tente o
seguinte: Clique
em run, no
menu superior, e
escolha a opco
Run with
Performance
Tool, depois
escolha Leaks.
Instruments !"!#
INSTITUTO DE ARTES INTERATIVAS
Clique em build,
no menu
superior, e
escolha a opco
Build and
Analyze.
Analisando mais a fundo !"!#
INSTITUTO DE ARTES INTERATIVAS
ExemploLeakViewController.m
O Instruments e o analisador so
nossos amigos e evitam problemas
futuros, use-os sempre!
Exerccios
1) Analise com o instruments e o
analisador todos aplicativos que voc j
fez, veja se h algo para corrigir!
Desenvolvimento
Luiz Gustavo Lino
Reviso
Lucas Longo
Omar Jardin Pavel
Edio
Primeira edio
Instituto de Artes Interativas
2010