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)
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.
: )
AS3 Loader for really beginners
May 7th, 2009
Hi for all, today i will explane something about the principiles of Actionscript 3: how to load an image inside the Flash. For totaly beginners, it’s so simple do it.
What the difference when load a picture using Actionscript 2 or 3?
Well, on AS2 you can call the file and imediatly when it loaded will appear inside the moviclip or stage. Using AS3 you can choice when and where the loaded file will appear.
AS3 Loader: your first loader inside Flash CS4
You need the Loader object and too create the listeners that will say for you what’s happen, if is loading, was an error or if the file is completely loaded. These listeners will be necessary always when you call a image or a XML file and others. Well, go to the Loader: see the code bellow:
1 2 3 4 5 6 7 8 9 10 11 12 | import flash.display.Loader; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.net.URLRequest; var request:URLRequest = new URLRequest("image.png"); var loader:Loader = new Loader(); loader.load(request); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadingImage); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadingError); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadingComplete); |
Here i created some differents listeners for the loader, the first, ProgressEvent.PROGRESS, will call the function loadingImage alway when the image is loading, inside the loadingImage you can create your preloader function using loader, get the bytes loaded and bytes total using the ProgressEvent inside the called function, something like this:
15 16 17 18 19 20 21 | var loaditPercent:uint; private function loadingImage(p:ProgressEvent):void { loaditPercent = Math.ceil( ( p.bytesLoaded / p.bytesTotal ) * 100 ); trace(loaditPercent); } |
The loaditPercent will show us the percent loaded. If you try your code will see that the image is loaded because the trace will show you 100% loaded but the image dont appear, need create the loadingComplete function and inside it we will put the loaded file inside of some movieclip or add it on the stage, you choose:
25 26 27 28 29 | function loadingComplete(e:Event):void { // addChild(loader); addChild(e.currentTarget); } |
This will add the loader, the picture, on the stage. Change the location using the MovieClip instance befora the addChild function. You can use too the loadingError function for your custom loader error, it’s so easy like others. Try it, for support comment here. Thanks for read.
Garbage Collector: System.gc();
May 6th, 2009
Hi again, sorry for the delay to write again. Here im Brazil, 1st May was a holly day and i was play with my son. Well here in agency we have some problens today with system memory of a AIR Project, the project play full HD videos and HD images into a 32″ LCD.
The problem: When i load videos and pictures, so much pictures, inside the project using Loader Class the memory will be always growing and growing and this will close sometime the application.
Solution: Like the post title, Garbage Collector. Well, the Garbage collector is alway actived by Flash Player, when i unload the Loader it will be send to the “trash” of Flash Player, and Garbaga Collector will define when delete the “trash” content, but we can tell to the Garbage Collector that “trash” is Ok to be deleted.
It’s so simple:
1 2 | import flash.system.System; System.gc(); |
If you have a custom loader class you can put the System.gc() into your unload public function to say to the Flash Player that the unloaded content it’s ok to be deleted.
1 2 3 4 5 6 7 | import flash.system.System; ... public function unloadcontent():void { _yourCustomLoader.unLoad(); System.gc(); } |
To force the Flash Player delete the content more speedily you can make a loop with 10 times calling the Garbage Collector:
1 2 3 4 5 6 7 8 9 10 11 | import flash.system.System; ... public function unloadcontent():void { _yourCustomLoader.unLoad(); // Calling System Garbage Collector loop for ( var gci:uint = 0; gci < 10; gci++ ) { System.gc(); } } |
The loop will force the Flash Player delete the content and make your app don’t crash.
It’s really easy, yeah? Try it, comment and if i save your life buy me a beer using the donation block in right side. Thanks for reading again
AIR – move, minimize and close application
April 23rd, 2009
Hi again folks, today working with AIR application i was searching something about control the window and database using Flash CS4, but today i will talk about only window control, close, minimize and move application window, its so simple do it, basically you need import only NativeApplication class, see the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package { import flash.desktop.NativeApplication; import flash.display.MovieClip; import flash.events.MouseEvent; public class DocumentClass extends MovieClip { public var closeBt :MovieClip; public var minBt :MovieClip; public var recordBox :MovieClip; public function DocumentClass():void { closeBt.addEventListener(MouseEvent.CLICK, closeApp); minBt.addEventListener(MouseEvent.CLICK, minApp); recordBox.addEventListener(MouseEvent.MOUSE_DOWN, dragApp); } } } |
We have now three functions: closeApp, minApp and dragApp. Three simple steps to take the window control, lets start with dragApp, the function that will drag your AIR Application using MOUSE_DOWN event.
Now we need put this private function inside the document class, bellow the code:
20 21 22 23 | private function dragApp(m:MouseEvent):void { stage.nativeWindow.startMove(); } |
The function will work only when mouse is down in the recordBox Movieclip, now you can drag your application using mouse moviment. Now to close and minimize the application you will use a simple CLICK event.
25 26 27 28 29 30 31 32 33 | private function closeApp(m:MouseEvent):void { NativeApplication.nativeApplication.exit(); } private function minApp(m:MouseEvent):void { stage.nativeWindow.minimize(); } |
To close the application using Flash CS4 you need use the NativeApplication and not only NativeWindow. But is so easy to use and now you can create your AIR application using a custom chrome. Try it!
Proportional Scale
April 20th, 2009
Well how do i scale my objects proportionally? Hmm this is a problem, but now a problem resolved. Now you can use the scaleObject class, a simple class that make only one thing: scale objects proportionally.
This is great to maximize images into the fullscreen stage or other things when you need create nicelly thumbnails, i used this class into the drag large images with zoom post, when the picture is loaded i put the code to contract the image size into the mask moviclip. Now i will explane some thing about it, look the simple code:
1 2 | import com.dLibs.utils.scaleObject; var so:scaleObject = new scaleObject(movieClip, { width : stage.stageWidth, height : stage.stageHeight }); |
Really simple? Yeah. You will need only create a scaleObject and into the constructor arguments put the movieclip or bitmap object that you want scale and into the second argument, the object, you put the min width and min height of your object or the stage, width and height receive numbers.
2 | var soTwo:scaleObject = new scaleObject(bitmap, { width : 500, height : 400 }); |
If the bitmap or movieclip have more width than height will show full height and hide the extra width.
You can download the scaleObject class using Google Code or with the link bellow.
Download: scaleObject class (203)
Drag large images updated: now with zoom
April 16th, 2009
Hi again, now i will show an update of the post Drag large images inside de box. Now the class dragIt have the option to use zoom in and out the content of the box.
Well, the primary function of the class that is drag the content inside the mask box continue the same, and you can see how work into the post: Drag large images inside de box. For the new feature you need re-download the class using the SVN address or download the sample on final of the this post.
So, i added a simple public function for this class to add the zoom in and zoom out movieclip into the dragIt object, named addZoom, and work so simple like show bellow:
1 2 3 4 | var drag:dragIt = new dragIt(); drag.drag(content,maskImage,true); drag.addZoom(more,less); addChild(drag); |
Its really simple, the line 3 you will set the instance name of the zoom in and zoom out moviclip and when you click in one of these clips the content movieclip will resize more or less depending the button that you clicked.
Other thing added into the dragIt class is the possibility to resize the image on start the class. If you see the line 2 of the code sample and compare with the same line in Drag large images inside de box post will see that the ultimate argument is true, by default this is set false but if you want load the new content and resize it for the width and height proportion only put the true as you latest argument.
Any questions comment the post and download the sample to test it.
Download: Drag image with zoom (383)
Navigation structure for Flash sites
April 14th, 2009
Post Edited: April – 16, 2009.
Hi, im Joisiney Leandro, new author of the DES84 Blog, and now i will talk something about the navigation structure that i created. This can manage all the navigation of your project, for small sites, more easily and speedily of you create your structure from zero.
What this structure do?
• Send click events for the Google Analytics.
• Create a protection block for the user cannot click in the same button more one time or click and two buttons when load the first. The final user may wait the transition to interact again with the menu links.
• Enable the forward and backward browser buttons.
• Change the page title and the URL address depending the link called.
• Return the progress event, percent loaded, when you load external data.
• Return the complete event and make the simple transition, fade in and fade out, and you can do your own transition when load external animations.
• You can create custom forward and backward buttons to use inside the Flash, this feature work only inside the browser, its good to full screen sites.
All the documentation of the classe is included in a implement document, the class used in this example is the NavegateAdressAnalitics, you can read the documentation into the ImplementsNavegateAdressAnalitics on the same folder of the class (only in portuguese ).
Well, go code. Here is the API’s that you need to use the navigation structure work fine. [SWFAdress, TweenLite, GAForFlash]
See the working sample clicking here: http://blog.des84.com/projects/navigation/
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 82 83 84 85 86 | package { import JrsAs.events.Events; import JrsAs.events.ProgressEvents; import JrsAs.pub.core.NavegateAdressAnalitics; import JrsAs.pub.shap.Rectangle; import JrsAs.str.core.SWFAddress; import flash.display.MovieClip; import flash.events.MouseEvent; import flash.text.TextField; public class Acesso extends MovieClip { public var mcDoc_group:MovieClip; public var mcDoc_Um:MovieClip; public var mcDoc_Dois:MovieClip; public var mcDoc_Tres:MovieClip; public var mcDoc_Quatro:MovieClip; public var mcDoc_Avancar:MovieClip; public var mcDoc_Voltar:MovieClip; //------------------------------ private var cot_transition:NavegateAdressAnalitics; private var mc_block:Rectangle; public function Acesso():void { mc_block = new Rectangle(); mc_block.jrs_Height = 300; mc_block.jrs_Width = 700; mc_block.jrs_ColorBG = 0xff0000; this.stage.addChild(mc_block); cot_transition = new NavegateAdressAnalitics(); cot_transition.jrs_SetDomain = "http://www.domeujeito.com.br"; cot_transition.jrs_SetUA = "UA-5351680-2"; cot_transition.jrs_SetMCBlockTransition = mc_block; cot_transition.jrs_SetArgsPag = {id:0, onLoad:Empresa, setTitle:"Empresa"}; cot_transition.jrs_SetArgsPag = {id:1, onLoad:Historia, setTitle:"História"}; cot_transition.jrs_SetArgsPag = {id:2, onLoad:"produtos.swf", setTitle:"Produtos", onLoadFunction:"jrs_TextParams", onLoadParams:["joice","rocha"]}; cot_transition.jrs_SetArgsPag = {id:3, onLoad:Contato, setTitle:"Contato", onLoadParams:["joice","rocha"]}; cot_transition.jrs_SetEditArgsPag = {id:3, setTitle:"Fale Conosco", onLoadParams:["joice 3","rocha 3"]}; cot_transition.addEventListener(Events.COMPLETE, jrs_complete); cot_transition.addEventListener(ProgressEvents.PROGRESSO, jrs_progress); mcDoc_group.addChild(cot_transition); SWFAddress.setInit("/0/Empresa"); mcDoc_Um.id = "/0/Empresa"; mcDoc_Dois.id = "/1/História"; mcDoc_Tres.id = "/2/Produtos" mcDoc_Quatro.id = "/3/Fale Conosco"; mcDoc_Um.addEventListener(MouseEvent.CLICK, click); mcDoc_Dois.addEventListener(MouseEvent.CLICK, click); mcDoc_Tres.addEventListener(MouseEvent.CLICK, click); mcDoc_Quatro.addEventListener(MouseEvent.CLICK, click); mcDoc_Avancar.addEventListener(MouseEvent.CLICK, avancar); mcDoc_Voltar.addEventListener(MouseEvent.CLICK, voltar); } private function click(event:MouseEvent):void { if(cot_transition.jrs_GetProximaPagina)SWFAddress.setValue(String(event.currentTarget.id)); } private function voltar(event:MouseEvent):void { if(cot_transition.jrs_GetProximaPagina)SWFAddress.back(); } private function avancar(event:MouseEvent):void { if(cot_transition.jrs_GetProximaPagina)SWFAddress.forward(); } private function jrs_complete(event:Events):void { //trace("event.info"); } private function jrs_progress(event:ProgressEvents):void { //trace(event.info.bytesLoaded); } } } |
Description of the Acesso.as
28 29 30 31 32 | mc_block = new Rectangle(); mc_block.jrs_Height = 300; mc_block.jrs_Width = 700; mc_block.jrs_ColorBG = 0xff0000; this.stage.addChild(mc_block); |
Creating the Movieclip that will block the access for the multiple clicks, for this the movieclip may added to stage.
34 35 36 | cot_transition = new NavegateAdressAnalitics(); cot_transition.jrs_SetDomain = "http://www.domeujeito.com.br"; cot_transition.jrs_SetUA = "UA-5351680-2"; |
The line 34 initialize the class and create the main objects, the line 35 and 36 create the Google Analytics object, you need put your site URL and your Google Analytics ID for this site, always use these two setter functions to GA for Flash work right.
37 | cot_transition.jrs_SetMCBlockTransition = mc_block; |
This setter function is not necessary but it will resolve some probably navigation problems, it set the object that will block the stage when have the transition.
39 40 41 42 | cot_transition.jrs_SetArgsPag = {id:0, onLoad:Empresa, setTitle:"Empresa"}; cot_transition.jrs_SetArgsPag = {id:1, onLoad:Historia, setTitle:"História"}; cot_transition.jrs_SetArgsPag = {id:2, onLoad:"produtos.swf", setTitle:"Produtos", onLoadFunction:"jrs_TextParams", onLoadParams:["joice","rocha"]}; cot_transition.jrs_SetArgsPag = {id:3, onLoad:Contato, setTitle:"Contato", onLoadParams:["joice","rocha"]}; |
These lines, 39 to 42, create the pages of your project. The setter function send an object with all data using two ways:
Loading an external SWF and use this parameters:
id:uint = id of the page, case have two links with the same name.
onLoad:* = the address of the external SWF file.
setTitle:String = set the Title of the page called.
onLoadFunction:String = this set the function name into the loaded file that will called when the file load is complete.
onLoadParams:Array = you can send here the parameters to onLoadFunction.
Importing class from the library
id:uint = id of the page, case have two links with the same name.
onLoad:* = classe/MovieClip name.
setTitle:String = set the Title of the page called.
onLoadFunction:String = in this case, attaching a class, you can choose if you call a function or not, if not use it but you send the parameters, these parameters will be send direct to constructor of the class.
onLoadParams:Array = you can send here the parameters to onLoadFunction or to constructor.
44 | cot_transition.jrs_SetEditArgsPag = {id:3, setTitle:"Fale Conosco", onLoadParams:["joice 3","rocha 3"]}; |
Using the jrs_SetEditArgsPag is possible change the data of the parameters of the pages created. If you create a product page and you want change the Title of the page when click in one or other product you can. Its easy like show the line 40.
51 | SWFAddress.setInit("/0/Empresa"); |
Here th API SWFAdress come and set the initial page, the first page that will be opened.
The format of the URL is: http://….com.br/index.html#/id/Titulo/ when id is the responsible for the navigation, change the id and you will change the page.
72 | if(cot_transition.jrs_GetProximaPagina)SWFAddress.back(); |
The Setter SWFAddress.back() only work right into the browser, and this make you go to the backward page.
76 | if(cot_transition.jrs_GetProximaPagina)SWFAddress.forward(); |
The Getter jrs_GetProximaPagina verify if you can go to the next page, case you go to a page and click in backward button, if possible, return true, and the setter SWFAddress.forward will make you go to the next page too.
You can download the sample here: Navigation Structure (231)
PS: into the SWF file that you will download, contain all class that you need to make the structure work fine, including GA for Flash, Tweenlite and SWFAddress. Other thing is, the post dont talk about the possible that remove the backward and forward button if is no necessary but this is possible.
Drag large images inside the box
April 13th, 2009
Hi, today i made a dragger to view large images inside the small mask and here i am to show for you how to use it if you need. Well, the dragger need only create a simple object and set the content movieclip and the mask movieclip instances, the classe do the rest. See the sample bellow.
You can click and drag the image into this box, you can put the box or with the width and height as you want and the same for the loaded image, you can use the size as you want too. But how to do it work fine ? Let’s go to the document class:
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 | package { import com.dLibs.events.Events; import com.dLibs.loadit; import com.dLibs.utils.dragIt; import flash.display.MovieClip; public class DocumentClass extends MovieClip { private var image:loadit; private var theImage:String = "http://farm4.static.flickr.com/3631/3375666390_505733a332_b.jpg"; public function DocumentClass():void { image = new loadit(theImage,true); image.addEventListener(Events.COMPLETE, imgComplete); image.addEventListener(Events.PROGRESS, imgProgress); content.addChild(image); } private function imgProgress(e:Events):void { // trace(e.obj.percentLoaded); } private function imgComplete(e:Events):void { var drag:dragIt = new dragIt(); drag.drag(content,maskImage); addChild(drag); } } } |
Here i load the Flickr image (Jesus Jones, Me and Joisiney Leandro) and only into the complete event i put the function that make the dragger. First step is create the dragIt object like show the line 29.
The second step is set the Movieclips, the content clip and the maks clip, using the Public Function drag. See the line 30, and add the object to stage aaand done. Test the movie and you can drag your own pictures into the mask, so easy. To make the sample you can download the sample bellow or only classes using the SVN repository: http://asdatalibs.googlecode.com/svn/trunk/
Download the sample project: Drag large images into the box (210)
Create, write and read file using AIR
April 9th, 2009
Hi for all again and today i will write here something about the File Class, how to create, read and write data into a file and store it in local machine.
Well, yesterday i had the problem to create a file log on an AIR project, for two hours i read some articles and sample chapters about File class and only today (now, 9 April @12:15) i resolve this problem: create a class to create and write data into the File.
The code sample is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import com.dLibs.air.recFile; var nFile:recFile = new recFile(); nFile.setDiretory = "diretoryName"; // fileText is a textfield fileText.text = ""; // saveButtom is a movieClip saveButtom.addEventListener(MouseEvent.CLICK, saveTheFile); function saveTheFile(m:MouseEvent):void { var theDate:Date = new Date(); var dateNow:String = String(theDate.getHours() + ":" + theDate.getMinutes() + ":" + theDate.getSeconds()); var textBox:String = String(dateNow + " : " + fileText.text + "\n"); nFile.writeData = textBox; // result sample: 13:08:32 : content of the textbox fileText.text = ""; } |
The default format of the file is HTM, but you can change it too using the first argument of the constructor like show bellow:
3 | var nFile:recFile = new recFile(“txt”); |
Well, to save the data you need call the public set function writeData, see line 17. The string that you send to writeData function will be write at the last line, case document type is HTM or HTML, or after the last character for other document types.
Fine, but where my file? Hmmm, see it. Using the complete constructor arguments you can set the document type, the folder that you want save the file and too the name of the document. No one of these arguments is necessary to create the file, by default the document will be save using type HTM, saved in the Desktop, but you can change to Documents folder for Mac and My Documents for Windows, and the last, name of the file will be the date: dd_mm_yyyy.
Other set function that you can use is the setDiretory. If you chosse to create the file into the Documents folder with extension txt and there you want create other folder with the name of the your AIR project, what you can do to make it ? It’s so simple:
var nFile:recFile = new recFile(“txt”,"documents"); nFile.setDiretory = "projectName"
This today will create a file named 09_Apr_2009.txt into your My Documents / projectName folder automatically, if there have this file you will write the data at the last line of this.
You can download the full source code using the download bellow, or you can download only the classes using the SVN client: http://asdatalibs.googlecode.com/svn/trunk/




