Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 3.0 (http://www.flasher.ru/forum/forumdisplay.php?f=83)
-   -   Загрузка картинка на сцену (http://www.flasher.ru/forum/showthread.php?t=179540)

abzhapparovmaxa 16.05.2012 22:33

Загрузка картинка на сцену
 
Доброго времени суток.
Можно ли как то ПОСТЕПЕННО загружать картинку? То есть видел флешки где виден сам процесс загрузки картинки. Картинка загружается постепенно с плохого качества в хорошее (сразу сначала появляется размытая картинка и постепенно эта размытие с картинки уходит).

П. С.
Просто делаю проект где загружаются "тяжелые" картинки. И долго смотреть на прелоадер скучно.

Заранее спасибо!

ChuwY 16.05.2012 23:34

Задумался над вашей задачей.
Почитал вот тут.

Решение (почти полная копипаста, только наглядности добавил):

Код AS3:

package
{
        import flash.display.Loader;
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.events.MouseEvent;
        import flash.events.ProgressEvent;
        import flash.net.URLRequest;
        import flash.net.URLStream;
        import flash.utils.ByteArray;
        import flash.utils.setTimeout;
 
        [SWF(width = "1200", height = "800")]
        public class test extends Sprite
        {
                private var url:String = "http://www.iclarified.com/images/news/20894/74775/74775.jpg"; //The url to the jpeg
                private var urlStream:URLStream = new URLStream(); //We will use this to progressively stream the bytes of the jpeg
                private var byteArray:ByteArray = new ByteArray(); //Bytes from the URLStream will go here
                private var _loaders : Vector.<Loader> = new Vector.<Loader>();
                private var _idx : uint;
                private var _currLoader : Loader;
                public function test()
                {
                        urlStream.load(new URLRequest(url));
 
                        urlStream.addEventListener(ProgressEvent.PROGRESS, onStreamProgress, false, 0, true);
                        urlStream.addEventListener(Event.COMPLETE, onStreamComplete, false, 0, true);
                        stage.addEventListener(MouseEvent.CLICK, clickHandler);
                }
 
                private function clickHandler(event : MouseEvent):void{
                        if(_currLoader){
                                removeChild(_currLoader);
                        }
                        if(!_loaders.length){
                                return;
                        }
                        _currLoader = _loaders[_idx % _loaders.length];
                        addChild(_currLoader);
                        _idx++;
                }
 
 
 
                private function onStreamProgress(evt:ProgressEvent):void
                {
                        // You could put a condition here to restrain the number of calls to updateBytes().
                        // Use the evt.bytesTotal and evt.bytesLoaded to help accomplish this.
                        // You will find that by limiting it, it will increase responssivness of your
                        // program and give an overall better result.
                        // Have it call updateBytes() every 100 bytes or so.
                        updateBytes();
                }
 
                private function onStreamComplete(evt:Event):void
                {
                        updateBytes(); // Call updateBytes one more time to load in the last bytes.
 
                        urlStream.removeEventListener(ProgressEvent.PROGRESS, onStreamProgress); // Clean after yourself
                        urlStream.removeEventListener(Event.COMPLETE, onStreamComplete); // Clean after yourself
 
                        // Somehow, without this, it does not work. You will end up with a ~90% loaded image
                        setTimeout(confirmBytesLoaded,500); // Would be nice if someone could tell me why this makes it work!!
                }
 
                private function confirmBytesLoaded():void
                {
                        updateBytes(); // As said earlier, you need to check it one last time it seems.
                        if (urlStream.connected) urlStream.close(); // Close the stream once you're done with it.
                }
 
                private function updateBytes():void
                {
                        // Important step. We copy the bytes from the stream into our byteArray,
                        // but we only want to add the new bytes to our byteArray, so we use the lenght
                        // attribute as an offset so that the new bytes gets added after the bytes that we added before.
                        urlStream.readBytes(byteArray, byteArray.length);
 
                        if(byteArray.length > 0) // Make sure there are new bytes to load.
                        {
                                var loader : Loader = new Loader();
                                loader.loadBytes(byteArray); // Use the Loader to decode the loaded bytes.
                                _loaders.push(loader);
                        }
                }
}


При этом необходимо использовать картинки в progressive jpeg для постепенного улучшения качества. При использовании обычного загрузка будет производиться по кускам.


Часовой пояс GMT +4, время: 13:16.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2024, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.