Galeria de imagens com AS3: FullGallery
November 18th, 2009
Hi Geral, depois de muito tempo e muitas mudanças na vida estou de volta escrevendo um novo post sobre alguma coisa que eu já deveria ter feito a muito tempo ehehe: uma galeria de imagens decente. Estive pesquisando algumas coisas sobre estrutura de navegação e formas de deixar o codigo As3 mais fácil de trabalhar, fiz bastante mudanças nas minhas classes e uma das primeira que tem esse mesmo conceito é a FullGallery: uma galeria de imagens estilo lightbox feita em Actionscript 3 que permite arquivos carregados externamente ou o próprio arquivo enviarem uma lista de imagens e chamar uma determinada foto usando a estrutura.
Primeira coisa que devemos fazer é baixar o pacote de classes novesfora via Google Code. Coloque a pasta novesfora junto do seu projeto ou na sua pasta de classes, a segunda opção é sempre a melhor. O resultado final será esse: http://blog.des84.com/projects/FullGallery/
Segundo passo é criar um arquivo FLA e setar o seu document class, no exemplo irei usar o nome da classe de ‘DocumentClass()’, ai precisamos definir primeiro o alinhamento da aplicação, se irá ser alinhado ao centro – default do Flash – ou se irá alinhar toda a aplicação à esquerda, vamos colocar alinhado à esquerda.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package { import flash.display.MovieClip; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; public class DocumentClass extends MovieClip { public function DocumentClass():void { // Configurando e setando stage infos stage.align = StageAlign.TOP_LEFT; stage.quality = StageQuality.BEST; stage.scaleMode = StageScaleMode.NO_SCALE; } } } |
Depois disso precisamos usar a classe StageLocation do pacote novesfora para falar para a aplicação, inclusive para a FullGallery – que usa essa classe na sua construção – quem é o Stage, a largura e também a altura do palco.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | package { import flash.display.MovieClip; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import novesfora.utils.StageLocation; public class DocumentClass extends MovieClip { public var Box :MovieClip; // Movieclip no palco public function DocumentClass():void { // Configurando e setando stage infos stage.align = StageAlign.TOP_LEFT; stage.quality = StageQuality.BEST; stage.scaleMode = StageScaleMode.NO_SCALE; StageLocation.setStage = stage; StageLocation.setStageWidthFix = 900; StageLocation.setStageHeightFix = 500; } } } |
Agora é criar o objeto FullGallery e adicionar os, necessários, botões de fechar a galeria, anterior, próxima imagem e o movieclip de carregamento. Todos esses movieclips devem ser setados como string, essa que deve ser o mesmo nome da classe desses movieclips na biblioteca.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package { import flash.display.MovieClip; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.MouseEvent; import novesfora.photos.FullGallery; import novesfora.utils.StageLocation; public class DocumentClass extends MovieClip { public var Box :MovieClip; private var $Gallery :FullGallery; private var $NewImages :Array; public function DocumentClass():void { // Configurando e setando stage infos stage.align = StageAlign.TOP_LEFT; stage.quality = StageQuality.BEST; stage.scaleMode = StageScaleMode.NO_SCALE; StageLocation.setStage = stage; StageLocation.setStageWidthFix = 900; StageLocation.setStageHeightFix = 500; // Criando a lista de imagens a serem mostradas $NewImages = new Array("imagens/001g.jpg","imagens/002g.jpg","imagens/003g.jpg"); // Criando o objeto da Galeria e configurando $Gallery = new FullGallery("LEFT"); // Alinhamento LEFT, default = CENTER $Gallery.addImages = $NewImages; // Adicionando imagens a serem mostradas $Gallery.addClose = "Closer"; // Adicionando botao para fechar - necessario $Gallery.addLoader = "loaderImage"; // Adicionando loader das imagens $Gallery.addNext = "nextImage"; // Botao de proxima imagem $Gallery.addPrev = "prevImage"; // Botao de anterior addChild($Gallery); } } } |
Até esse momento o que fizemos foi configurar a galeria, falar quem são os botões que serão usados, o alinhamento do palco e adicionamos a galeria no projeto, não chamamos em nenhum momento uma fotografia, ou seja, se compilar o projeto nesse estágio verá que nada acontecerá. Agora irá depender mais de você que da galeria, você irá receber os thumbnails via XML, AMFPHP ou qualquer outra forma que quiser, montar sua grid e esse thumbnail quando for clicado irá executar uma função da FullGallery dizendo qual é a imagem, dentro do Array de imagens já enviado, que precisa ser aberta. Funciona da seguinte forma, ver as funções ShowFirstImage(), ShowSecondImage() e ShowThirdImage():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | package { import flash.display.MovieClip; import flash.display.StageAlign; import flash.display.StageQuality; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.MouseEvent; import novesfora.photos.FullGallery; import novesfora.utils.StageLocation; public class DocumentClass extends MovieClip { public var Box :MovieClip; private var $Gallery :FullGallery; private var $NewImages :Array; public function DocumentClass():void { // Configurando e setando stage infos stage.align = StageAlign.TOP_LEFT; stage.quality = StageQuality.BEST; stage.scaleMode = StageScaleMode.NO_SCALE; StageLocation.setStage = stage; StageLocation.setStageWidthFix = 900; StageLocation.setStageHeightFix = 500; // Criando a lista de imagens a serem mostradas $NewImages = new Array("imagens/001g.jpg","imagens/002g.jpg","imagens/003g.jpg"); // Criando o objeto da Galeria e configurando $Gallery = new FullGallery("LEFT"); // Alinhamento LEFT, default = CENTER $Gallery.addImages = $NewImages; // Adicionando imagens a serem mostradas $Gallery.addClose = "Closer"; // Adicionando botao para fechar - necessario $Gallery.addLoader = "loaderImage"; // Adicionando loader das imagens $Gallery.addNext = "nextImage"; // Botao de proxima imagem $Gallery.addPrev = "prevImage"; // Botao de anterior addChild($Gallery); // Mouse Events - Fazendo o *** menu funcionar ( Box.Box01 as MovieClip ).buttonMode = true; ( Box.Box02 as MovieClip ).buttonMode = true; ( Box.Box03 as MovieClip ).buttonMode = true; ( Box.Box01 as MovieClip ).addEventListener(MouseEvent.CLICK, ShowFirstImage); ( Box.Box02 as MovieClip ).addEventListener(MouseEvent.CLICK, ShowSecondImage); ( Box.Box03 as MovieClip ).addEventListener(MouseEvent.CLICK, ShowThirdImage); stage.addEventListener(Event.RESIZE, ResizeBox); stage.dispatchEvent(new Event(Event.RESIZE)); } private function ShowFirstImage(e:MouseEvent):void { $Gallery.initGallery(); // Valor default = 0. Primeira imagem do Array } private function ShowSecondImage(e:MouseEvent):void { $Gallery.initGallery(1); // Chama por 1, segunda imagem do Array } private function ShowThirdImage(e:MouseEvent):void { $Gallery.initGallery(2); // Chama por 2, terceira imagem do Array } private function ResizeBox(e:Event):void { Box.x = ( stage.stageWidth - Box.width ) / 2; Box.y = ( stage.stageHeight - Box.height ) / 2; } } } |
Usando o $Gallery.initGallery(); iremos chamar a class FullGallery e inicializar a galeria enviando o ID da imagem que corresponde ao numero da posição do Array de imagens, bem simples. Como já foi dito, o resultado final será esse: http://blog.des84.com/projects/FullGallery/. Se preferir pode baixar os arquivos diretamente pelo link abaixo, o projeto requer o uso das classes Tweenlite e do pacote novesfora via Google Code.
Download: FullGallery Source Code (395) (Defasada)
Download versão nova: FullGallery Atualizada (177)
Flash CS5 on FOTB
September 23rd, 2009
A great preview about new version of Flash CS5 with integration with Flash Builder, reading custom classes and so much more. Play the video bellow and have fun.
Adobe Flash CS5 Viper presented on FOTB 2009! – www.CS5.org from Adobe CS5 on Vimeo.
Carregando imagens em AS3 sem usar a classe Loader()
September 22nd, 2009
Depois de tanto ouvir acabei voltando a escrever no blog em português, mas isso acredito que é o que menos importa até mesmo porque estamos ali meio a meio com os americanos em quantidade de acessos no blog mas com muito mais tempo online para os brasileiros, então ponto pra gente.
Bem vou falar hoje de uma classe personalizada que criei para carregamento de imagem. Quando digo que não irá utilizar a classe Loader(), eu tenho alguns argumentos para isso:
- ao usar a classe loader você precisa colocar o conteúdo dela dentro de um sprite ou movieclip para poder manipular.
- ao deletar o loader precisa remover todos os listeners criados para o carregamento
- precisamos criar listeners adicionais para recuperar no inicio do carregamento o tamanho da imagem
- cache – i hate you – quem nunca teve problemas com atualizar o conteúdo e mesmo depois de horas continuar aparecendo a mesma imagem que o cliente implorou para trocar e você ja trocou, mas vai explicar pra ele o que é cache.
Com a classe personalizada, que estende à movieclip, temos uma facilidade muito maior de manuseio porque depois de criado o objeto podemos tratá-lo como um movieclip comum. Para tanto vamos usar eventos personalizados para sabermos quando estiver carregando, carregado, erro ao carregar e dimensões da imagem no inicio do carregamento. Abaixo vou deixar um exemplo mostrando o funcionamento, tudo que é feito nesse exemplo pode ser feito usando a classe nativa Loader() mas de uma forma muito mais fácil.
Então, para começarmos precisamos da classe de carregamento, dos eventos e da unica dependência que é a classe do Anttikupila, JPGSizeExtractor, essa que retira da imagem no carregamento a sua largura e altura – antes do complete. Para fazer download das classes você poder usar o seu programa de SVN e baixar o repositório: http://asdatalibs.googlecode.com/svn/trunk/ ou se preferir acesse o browser de códigos do Google Code clicando aqui.
Agora que temos todas as classes então vamos ao código. Dentro do nosso document class vamos criar a variável e um listener para o botão que temos no palco do Flash, botão esse que será responsável por chamar a imagem que queremos carregar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package { import flash.display.MovieClip; import flash.events.MouseEvent; import novesfora.loader.LoadFile; public class DocumentClass extends MovieClip { public var downImage:MovieClip; public var conteudo:MovieClip; private var lf:LoadFile; private var imageURL:String = "http://blog.des84.com/imageSamples/thinkGeek_largeSize.jpg"; public function DocumentClass():void { downImage.buttonMode = true; downImage.addEventListener(MouseEvent.CLICK, downloadImage); } } } |
Até esse ponto o que fizemos foi, criamos uma variável chamada lf do tipo LoadFile, que é a nossa classe personalizada e fizemos com que o movieclip ‘downImage’ fosse tratado agora como um botão, e quando for clicado irá executar a função chamada ‘downloadImage’. Vamos à essa função então:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package { import flash.display.MovieClip; import flash.events.MouseEvent; import novesfora.events.Events; import novesfora.loader.LoadFile; public class DocumentClass extends MovieClip { public var downImage:MovieClip; public var conteudo:MovieClip; private var lf:LoadFile; private var imageURL:String = "http://blog.des84.com/imageSamples/thinkGeek_largeSize.jpg"; public function DocumentClass():void { downImage.buttonMode = true; downImage.addEventListener(MouseEvent.CLICK, downloadImage); } private function downloadImage(e:MouseEvent):void { lf = new LoadFile(imageURL,true); lf.addEventListener(Events.COMPLETE, showFull); lf.addEventListener(Events.IOError, showError); lf.addEventListener(Events.PROGRESS, showProgress); lf.addEventListener(Events.START, showStart); } } } |
Aqui temos que o lf foi criado como um novo LoadFile, a sintaxe dessa classe recebe no seu document class dois valores como podemos ver, o primeiro do tipo String vai ser o endereço da imagem a ser carregada, que seria colocada dentro do URLRequest() caso estivéssemos utilizando a forma convencional de carregar um arquivo. O segundo valor do tipo Boolean define se o conteúdo carregado irá ou não receber o smooth para o bitmap, funcionalidade muito interessante quando tratamos de imagens que irão ser esticadas como quando utilizamos imagens para o background do site, por default esse valor é false para economizar processamento.
Abaixo então temos os eventos personalizados, Events(), para isso precisamos importar a classe de eventos como mostra 06 do código. Então temos, na sequência, um evento para o final do carregamento do arquivo, para erro ao carregar, progressão ou loading e para o inicio do carregamento, esse último para recebermos as dimensões do arquivo. Na frente de cada evento o nome da função que cada um irá executar. Então finalizando:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package { import flash.display.MovieClip; import flash.events.MouseEvent; import novesfora.events.Events; import novesfora.loader.LoadFile; public class DocumentClass extends MovieClip { public var downImage:MovieClip; public var conteudo:MovieClip; private var lf:LoadFile; private var imageURL:String = "http://blog.des84.com/imageSamples/thinkGeek_largeSize.jpg"; public function DocumentClass():void { downImage.buttonMode = true; downImage.addEventListener(MouseEvent.CLICK, downloadImage); } private function downloadImage(e:MouseEvent):void { lf = new LoadFile(imageURL,true); lf.addEventListener(Events.COMPLETE, showFull); lf.addEventListener(Events.IOError, showError); lf.addEventListener(Events.PROGRESS, showProgress); lf.addEventListener(Events.START, showStart); } private function showFull(e:Events):void { conteudo.addChild(lf); } private function showError(e:Events):void { trace("Error on load Image"); } private function showProgress(e:Events):void { trace("Total em KB é" + e.obj.TotalBytes + " kb" + " e o percentual carregado é: " + e.obj.PercentLoaded + " %"); } private function showStart(e:Events):void { trace("Largura: " + e.obj.width + " / Altura: " + e.obj.height); } } } |
No final então temos as funções executadas em cada momento:
A função showFull() irá adicionar o objeto lf do tipo LoadFile, que é a nossa imagem declarada pela variável imageURL, assim nesse momento, irá aparecer a imagem carregada.
A função showError() irá ser executada no momento que o arquivo chamado não for encontrado, ou não existe ou com o endereço da imagem declarado errado.
A terceira função é a showProgress(), essa será executada o tempo todo enquanto o arquivo estiver sendo carregado, nela podemos receber através de um objeto o percentual carregado, total em kb do arquivo requisitado e total carregado. Se observarmos essa função no código acima podemos ver que ao retornar ao evento progress podemos chamar os valores acima citados, como o percentual carregado, da seguinte forma: e.obj.PercentLoaded, sendo que ‘e’ é o Events, obj é nosso Objeto de valores e PercentLoaded é o valor em % carregado.
A última função é executada no inicio do carregamento do arquivo, showStart() e irá retornar a largura e altura da imagem assim como foi feito no Progress, so que o valor agora do objeto é width para largura e height para altura da imagem.
Valeu pelo tempo lendo o post e um grande abraço. Você pode fazer o download do exemplo acima no link abaixo.
Download: Carregando imagens em AS3 sem Loader() (265)
Flash Camp Brasil
September 15th, 2009
Galera interativa, é isso mesmo que vocês leram no titulo do post. Quem dá sempre uma olhada no blog do Lee Brimelow viram que haverá ainda nesse ano em países próximos ao Brasil como Chile, Argentina, Peru entre outros o Flash Latin Tour onde ficamos de fora por questões aparentemente técnicas. Mas o bom de tudo isso que em 2010, especificamente em Janeiro, bem no comecinho do ano, vamos ter o Flash Camp Brasil, evento que irá reunir boa parte da galera que programa em Flash, designers e todos que tem o interesse de aprender mais com os caras que estão ai pelo mundo fazendo a coisa girar e aparecer sempre coisas novas.
Então vamos ao Camp galera e sorte a todos ai.
Site: Flash Camp Brasil
Frameworks for Flash: 15 awesome to inspire you
July 14th, 2009
From Flashden: “As more and more developers turn to ActionScript 3, more and more AS3 frameworks appear to be popping up to assist the Flash community. Frameworks are basically reliable libraries of code that you can use to rapidly deploy a project while also streamlining common tasks. Think of them as a way to help develop and glue together the different components of a software project.”
Here you will see 15 AS3 Frameworks to inpire you and your next projects, making more rapidly and more efficient the job. Read it.
Link: 15 awesome actionscript 3 frameworks to inspire your next project
Rainbow Live XML Editor + CMS
July 10th, 2009
Rainbow Live XML Editor makes editing easy and full online with a simple Flash interface, multiple users and so much more. With Rainbow Live you can edit your @attributes, CDATA, upload your imagens and create thumbnails easely from your computer to server in seconds.
Rainbow Live puts the power back into the hands of Flash developers. There’s no more need to rely on a backend developer to build and maintain a database. Rainbow Live saves time and money as the process of setting up XML structures is familiar to many Flash developers and is made even more intuitive with Rainbow Live’s node-based approach. It allows for full control over a developing Flash project; if you’re building a bingo game or even a site navigation GUI, the access to Rainbow Live’s suite of time-saving tools is a priceless investment for people who want to develop and code at speed without relying on third parties to do the leg work.
Today you have two choices, Rainbow XML Editor and Live version, the most complete for only 99$ USD:
| Rainbow XML Editor
• Edit XML files on your hard drive |
Rainbow Live XML Editor + CSM
• All the functionality of Rainbow |
Rainbow Live puts the power back into the hands of Flash developers. There’s no more need to rely on a backend developer to build and maintain a database. Rainbow Live saves time and money as the process of setting up XML structures is familiar to many Flash developers and is made even more intuitive with Rainbow Live’s node-based approach.
Installing and Configuring your Rainbow Live XML Editor + CMS
First step is create a folder with the name as you wish. Now you can upload all files inside this folder. You will receive one SWF file, 3 PHP files for alternative FTP and a read-me.txt.
Well, you can create your custom INDEX file to your ‘Rainbow.swf’ file. Now you can access Rainbow.swf or your custom INDEX file. When you load the page will require Login and Password, the DEFAULT is:
Username: admin
Password: password
When you load the main page will see at first time the Project window, here you will create XML, import your own local file and edit this file so simple. But after uploaded and logged you must go to second step, add your registration code and configure your FTP access.
Go to Preferences tab, will show you Settings items. The first item is Registration. Click on arrow and set ‘domainkey’ your registration code, you can get your own on Rainbow Site.
After that you can change FTP access, it will able you to edit online your XML file. To edit it you may go to Preferences > FTP and change the ‘ftphost’ to your domain ftp, ‘ftpmode’ continue normal, ‘ftpusername’ is your FTP username and last ‘ftppassword’ is your FTP password, close this window and click on SITE option, you may change your ‘rainbowfolder’ example: “httpdocs/rainbowFolder/”, after that close the SITE window and click in SAVE (top-right window).
Rainbow Live XML Editor can create or edit only one XML file, one XML for one project. When you create one file, by Default, it is located on folder DATA/ inside folder that you install Live Rainbow but you have a choice to edit it and change the location of the file.
Editing XML file
It’s so simple, you can create nodes using “+” Plus button or add @attributes and images using right arrow, when you click will appear one window with all options, you can change add one attribute or CDATA text.
Using @attributes you can set one parameter like image and upload direct from your Rainbow Live to your server and add the address to your XML file, this moment you can select option to create thumbnail and add too into XML, great for portfolio and photogalleries. See the upload image bellow:
You can get more information on Rainbow Website or comment here.
Thanks a lot and cya.
New Adobe Browserlab
June 3rd, 2009
A new way to test your web project using cross browser and operating system is Browserlab by Adobe. Now you can put your project URL and see full page using a lot browsers with Windows, Mac OS, Linux and others.
If you alread have the Adobe ID you may go to Adobe Browserlab – link bellow – make login and use this new feature by Adobe, its fine to do. Try you too.
Link: Adobe Browserlab
AS3 Scrollbar: Scrollbase Class [Updated]
May 18th, 2009
Hi again, i update my scrollbar AS3 Class, named scrollbase, and today i post it for download, it’s really ease to work and so smaller than past version, only 1.5 kb.
The Features:
• Small file size
• Ease effect (or not) when move content
• Click the scroll background to move
• Full customizable
• Scroll dragger with dynamic size
• All in one line
To use it you can write only two lines, so easy. The first line is the import and the second line is the scrollbase constructor, you need only put inside the constructor basicaly four movieclips, like show the sequence: content movieclip, mask of the content movieclip, the dragger movieclip and last movieclip is the background of the dragger, where the dragger will slide. Show the sample code bellow:
import com.dLibs.utils.scrollbase; var sb:scrollbase = new scrollbase(conteudo,mascara,dragger,background,5,30);
This code show that ‘conteudo’ is the content movieclip and will be mask for ‘mascara’. ‘dragger’ is the movieclip that you click and move to see the rest of the content and move this movieclip upper of ’background’ movieclip. So easy, but there we have some more arguments.
The fiveth argument is the Ease speed, you can change for more or less ease effect, by default the ease uint is 1 (one). The sixth argument is the bottom padding, you can put a number in pixels to show after the content movieclip, so much good for full background scrollbar, by default this padding is 0 (zero).
When you need you can verify if the scrollbase is necessary using the public function verifyHeight(). You can change the content of the moviclip and verify if content movieclip have the height propertie bigger than your mask. Usage:
import com.dLibs.utils.scrollbase; var sb:scrollbase = new scrollbase(conteudo,mascara,dragger,background,5,30); sb.verifyHeight();
You can download and change if you need. Try it!
Download the Scrollbase sample and independent class (1487)
Scrollbase by Scrollbar for AS3 is licensed under a Creative Commons Attribution 3.0 United States License.
Based on a work at code.google.com.
26 July ‘09 /EDIT —————————–
I’m working in a new version of scrollbase and as soon as possible i will post here the classe code and samples, now im working with a temp class named scrollbasic that i made to resolve the problem that @sonia said in comment. You can download the scrollbasic with link bellow and as so simple to use like scrollbase:
import com.dLibs.utils.scrollbasic;
var nsc:scrollbasic = new scrollbasic(DataRecord.getDocumentClass, conteudo, mascara, sdragger, sbground);
Need set the main document class, you can create one static class to set and get it, and set the movieclips as content clip, mask clip, dragger clip and scrollbar background. Probabily i will post the new version of scrollbase 31 July ‘09.
Thanks for all and sorry for the error.
: )
Flex now is Flash Builder
May 18th, 2009
Yes, Flex Builder now is named Flash Builder and will be the Flash Platform Coder for Actionscript inside the Adobe Creative Suite CS5. Lee Brimelow write in your blog, The Flash Blog:
We at Adobe expected that the renaming of Flex Builder to Flash Builder would cause quite a bit of conversation in the community and indeed it has. After waking up this morning and reading all the reactions on various blogs and on Twitter, I feel like I need to answer some of the questions and concerns people have.
There you can see some answer for these questions:
• Are you planning on phasing out the Flash IDE?
• Isn’t it going to be more confusing when talking with clients about Flex?
• This screws up my resume and will make job interviews confusing won’t it?
• Will Flash Builder still be based on Eclipse?
• What about the Flex SDK?
XML and AS3 for beginners
May 15th, 2009
Hi guys, now we say something about how load and use the XML file as data base inside the Flash project using Actionscript 3.
First we need load the XML file to read these data inside the Flash. To do it create first a variable of URLLoader and other URLRequest. Different that when we load images, here need use the URLLoader() and not the Loader() class. Go to the first step:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | package { import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; public class loadXML { private var xmlLoader:URLLoader; private var xmlRequest:URLRequest; private var newXML:XML; public function loadXML():void { xmlLoader = new URLLoader(); xmlRequest = new URLRequest("dataXML.xml"); xmlLoader.load(xmlRequest); xmlLoader.addEventListener(Event.COMPLETE, dataLoaded); } public function dataLoaded(e:Event):void { newXML = new XML(e.target.data); trace(newXML); } } // End Class } // End Package |
The sample code will load the XML using URLLoader and using the URLRequest, inside the URLRequest you will put the XML file address. After that may create the Listener to say when XML file is loaded or loading or all that happened.
Inside the dataLoaded() function you will see that the newXML:XML() receiving the loaded data and creating your new XML file. Yes, now we can use the data to put inside the project, well lets go to the second step, first see the XML file:
1 2 3 4 5 6 | < ?xml version="1.0" encoding="utf-8"?> <gallery title="Gallery Name" author="Author Name"> <picture title="title of the first picture">/images/files/001.jpg</picture> <picture title="title of the second picture">/images/files/002.jpg</picture> <picture title="title of the last picture">/images/files/003.jpg</picture> </gallery> |
This time we have all the xml data inside the newXML() variable, to use these data it’s so simple, first we need to think that the first tag of the XML file is our newXML variable, if we call the newXML.@title will retrieve the title of the gallery tag. The same can do it to retrieve the author parameter value.
Well, if you retrieve the data from the gallery tag the rest is so easy. Let’s now retrieve the picture value, see the sample inside the dataLoaded() function:
24 25 26 27 28 29 | public function dataLoaded(e:Event):void { newXML = new XML(e.target.data); trace(newXML.picture[0].text()); // result : /images/files/001.jpg trace(newXML.picture[0].@ title); // result : title of the first picture } |
Or you can take the picture tag number and make a loop with these data, to get the picture quantity you need only get the array lenght():
26 27 | var newXMLQnt:uint = newXML.picture.length(); trace(newXMLQnt); // result : 3 |
Now you can create your own code using the sample codes, it’s so easy to do it, load and use the XML data inside the Flash using Actionscript 3. Try it and if have some difficulties comment here. Thanks for read and Cya.








