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 (208)
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() (157)
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
GreenSock Tweening Platform v11 Beta
July 17th, 2009
Yes, GreenSock Tweening Platform v11. Beta, really but awesome. The first, and the best, thing to me is Timeline (Lite/Max) that can do really good animation sequence.
On the heels of releasing the huge v10 update that introduced the plugin architecture, I’ve been hard at work on an even bigger release that delivers quite a few exiting improvements to the GreenSock Tweening Platform. Version 11 represents some significant changes to the guts of the code, so before officially releasing it, I wanted to post it in “Beta” form to give everyone a chance to not only test the code but also share their thoughts and suggestions. I’m also thrilled to announce that Grant Skinner (author of gTween) will be collaborating with me on upcoming versions (see separate announcement).
You can now create one TimeLineMax or TimeLineLite and run one or more animations, TweenLite or Max too, and you will use one only import. Great, you can read more about and see the sample on GreenSock WebSite or direct using link bellow:
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
5 free Rainbow Live licences to give away
July 13th, 2009
Code and Visual has 5 free Rainbow Live licences to give away to the 5 best Rainbow Live tutorial entries. For a limited time you can trial a fully functional installation of Rainbow Live on any server you choose by using the Domain Key tutorialcompetition. This Domain Key will remain valid for the duration of the competition.
Rainbow Live fills the niche between complete Flash CMS solution and XML Editor. Rainbow was built specifically to enable Flash developers to continue building XML based Flash files the way they usually do, while providing important CMS functionality out of the box with no changes needed.
Competition Details
The competition is open to anybody that wishes to write a tutorial about Rainbow, be it a webmaster or blog author, or even someone that submits a word document. The best tutorial bearing the title from each of the following 5 categories will each receive a free Rainbow Live Domain Key for the domain of their choice worth $99.
* Rainbow Live Flash CMS Installation Tutorial
* Rainbow Live Flash CMS Using Templates
* How to Use Rainbow Live as a Flash CMS
* Rainbow Live Flash CMS Using Custom Server Side Scripts (php)
* Rainbow Live Flash CMS Using Custom Server Side Scripts (.Net)
The winning entries will be placed on codeandvisual.com with full credit and links back to the original author site. All other entries will be linked to from the codeandvisual.com tutorials page.
What Entries Will be Judged On
* Simple and clear communication style
* Explaination of concepts and details
* Well written and entertaining style
* Good layout and presentation
* Use of images
How To Enter
Any tutorial that sends a ping back to http://www.codeandvisual.com/rainbow will be automatically entered. If you don’t own a blog, or can’t ping back, simply send your completed entry to competition [at] codeandvisual.com
Competition Deadline
The Competition will close 11:59 July 31st 2009, GMT
Some of the key benefits of Rainbow Live:
* Works with your current XML file
* Admin and User log-ins
* customisable node locking/hiding for client
* Easier for clients to use than a raw XML file
* Edit XML files live online
* Upload Images and files
* Automatically create thumbnails
* Define child templates to define your own node type
* No backend scripting necessary
* Customizable scripts
* Doesn’t dictate structure of your data/website
* Easily design the CMS to your own needs
To learn more about Rainbow Live and download an installation package.
visit: http://www.codeandvisual.com/rainbow-live
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. 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.
SVN with large files
July 9th, 2009
Hi guys, when we work with Flash for web sites or AIR applications is so easy use SVN to save and compare documents online or in your own local network, but when your job include large files – something near 3GB – like HD videos, After Effects video format and others, you will have some difficulties to commit these files.
You can easy increase the file size acceptable in your SVN Server, like Visual SVN, you must add the following line:
1 | http-library=serf |
to C:\Documents and Settings\
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








