Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 3.0 (http://www.flasher.ru/forum/forumdisplay.php?f=83)
-   -   XML во флэш, и еще раз в него же. (http://www.flasher.ru/forum/showthread.php?t=111970)

Varnol 14.05.2008 06:24

XML во флэш, и еще раз в него же.
 
:wacko:
Есть "простая" AS 3.0 галерея (с камментами), которая подгружает свой контент из xml. Галерея так же умеет подгружать другие XML, для обновления списка картинок.
(http://www.blog.noponies.com/archives/16)
Нужно сделать так, чтоб путь к XML файлу для "второй" (третьей, н-ной галереи) брался из ноды изначального XML файла.

(Грубо говоря, загрузилось gallery1.xml:
<images>

<pic>
<thumb>tn/1.jpg</thumb>
<largeimg>1.swf</largeimg>
<about>
<![CDATA[ктоздесь]]>
</about>
<next>gallery10.xml</next>
</pic>
Тыкнули на tn/1.jpg, некая переменная получила значение "gallery10.xml", тыкнули на "обновить XML" - вместо gallery1.xml загрузилось то самое "gallery10.xml".

Вроде бы примерно понял, как работает сама галерея, но нужную фичу, самостоятельно, кажется, не рожу. Впрочем, если найдутся бескорыстные люди, готовые просто подсказать - буду весьма благодарен.

Если есть желающие именно эту конкретную функцию реализовать\обьяснить как работает - за деньги -, готов оплатить ваше время; делается учебный проект, причем учусь я не на программиста.
Пишити камменты или на varnol@yandex.ru

MrPoma 14.05.2008 06:44

Покажите Ваш код.

Varnol 14.05.2008 14:35

Там, по ссылке, лежит исходник as is.
(http://www.blog.noponies.com/wp-cont...allery_v13.zip)

Код сюда целиком не влазит из-за ограничения на кол-во символов... Если только кусками:
Код:

//import tweening engine tweenLite
import gs.TweenLite;

//set up stage
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;

/*********************************************************************
LOAD THE XML
**********************************************************************/

//xml load variables
var xmlLoader:URLLoader;
var xmlData:XML;

//xml load function
function loadXml(xmlFile:String):void {
        xmlLoader= new URLLoader();
        xmlData = new XML;
        xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
        xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, xmlLoadFail);
        xmlLoader.load(new URLRequest(xmlFile));
}
//load the XML file
loadXml("2ch.xml");

function xmlLoadFail(event:IOErrorEvent):void {
        trace("Looks like there was an error loading the XML");
}

//we have our XML data, so lets load the thumbnails
function xmlLoaded(e:Event):void {
        xmlData = XML(xmlLoader.data);
        loadThumbs();//call the thumbs loading function
}

/*********************************************************************
LOAD THE THUMBNAILS
**********************************************************************/

var p:int = 0;//increment value
var changex:int = 0;//var to track total width of thumb track
var padding:int = 50;//use if you want padding between thumbnails in the scroller
var pictureValue:int = 0;//dynamic var used to track position in XML data array
//var for empty movieClip that hold our thumbs
var child:MovieClip;
//generic empty loader object
var loader:Loader;
var thumbLoader:Loader;
//Sprite holder for content to load into
var largeContent:Sprite = new Sprite;
addChild(largeContent);//add it to stage
//number of thumbs to show
var visThumbs:int = 5;
//load in the thumbnails
function loadThumbs():void {
        thumbLoader = new Loader();
        thumbLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadThumbProgress);
        thumbLoader.contentLoaderInfo.addEventListener(Event.INIT, thumbLoaded);
        thumbLoader.load(new URLRequest(String(xmlData.pic.thumb[p])));//access the thumbnails
        p++;//increment through the thumbnails array

        //progresshandler for thumbs loading.
        function loadThumbProgress(e:ProgressEvent):void {
                //trace("LOADED "+Math.floor(e.bytesLoaded / 1024)+ " OF "+Math.floor(e.bytesTotal/1024));
        }

        //we have access to our clips properties, so lets add it to the thumbs scroller
        function thumbLoaded(e:Event):void {

/*CALL SCROLL CONSTRUCTOR FUNCTION!!!
here we create a function that runs only once that calls the thumbnails constructor function
its placed here so we can access the properties of our thumbnails like width and height.
simply delete this if statement and populate the vars further down in the script to set up
your thumbnails scrolling manually. Make sure to call the constructor "constructScroller()" function as well*/

                if (pictureValue==0) {
                        //scroller pane specfic setup
                        scrollPaneX = 50;
                        scrollPaneY = 400;
                        scrollPaneWidth = thumbLoader.content.width*visThumbs+(padding*(visThumbs-1));//mask
                        scrollTrackWidth = thumbLoader.content.width*xmlData.pic.length()+(padding*(xmlData.pic.length()-1))//scrolltrack
                        scrollPaneHeight = thumbLoader.content.height;
                        constructScroller();//call the scroller constructor function
                }
                child = new MovieClip();
                //dynamic var to give us and index position, meaning we can access the associated large image
                //residing in this XML node.
                child.pictureValue = pictureValue++;
                child.addChild(thumbLoader.content);
                //event listeners for rolling over and clicking thumbnails
                child.addEventListener(MouseEvent.MOUSE_OVER, overThumb);
                child.addEventListener(MouseEvent.MOUSE_OUT, offThumb);
                child.addEventListener(MouseEvent.CLICK, loadBigImage);
                //add the content to the thumbs track
                holder_mc.addChild(child);
                TweenLite.from(child, 3, {alpha:0});//alpha in the thumbnails
                //shuffle the content along, so we get a nice spread of thumbnails
                child.x =changex;//set the x pos of the thumb to the changex var
                changex = changex+thumbLoader.content.width+padding;//increments thumb x valeu in thumbs track + adds in any padding.
                //child.buttonMode = true;//uncomment if you want a hand cursor
                //add in some info about amount of thumbs here
                thumbLoad_txt.text = "LOADED "+p +" OF "+(xmlData.pic.length ())+" THUMBNAILS";
                if (p<xmlData.pic.length()) {
                        loadThumbs();//create loop
                }
                if (p==xmlData.pic.length()) {
                        //add the scroll listeners when we have content and its ready to scroll
                        //this if test below checks to see if there are enough thumbnails to actually need the scroll listeners
                        if(child.width*p+(padding*(p-1))>scrollPaneWidth){
                        addScrollListeners()
                        }
                        //clear the loading thumbs text
                        thumbLoad_txt.text = "";
                        //demo loading in larget image via non click method
                        //loadBigImage(null, 2)
                }
        }
}



/*********************************************************************
LARGE IMAGE LOADING - HANDLE A CLICK ON THUMBNAIL
**********************************************************************/
function loadBigImage(event:MouseEvent = null, pictureToLoad:int = undefined):void {
       
        var targetThumbs:int
        //test to see if we have a mouse event or a simple function call
        if(event != null){
        targetThumbs= event.target.pictureValue;
        }else{
                targetThumbs = pictureToLoad
        }
        //create a loader to handle loading in the large clip
        loader = new Loader();
        loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadLargeProgress);
        loader.contentLoaderInfo.addEventListener(Event.INIT, loadLargeInit);
        loader.load(new URLRequest(String(xmlData.pic.largeimg[targetThumbs])));

        //clean up for new content
        TweenLite.to(largeContent, .5, {alpha:0});//alpha out the large image
        outPut_txt.text = "";//clear any previous descriptions text

        //simple load progress bar, extends across top of stage
        //You can remove this, just make sure you remove other references to it later in the script below.
        var loadBar:Sprite = new Sprite;
        loadBar.graphics.beginFill(0x33FFFF);
        loadBar.graphics.drawRect(0, 0, 1, 2);
        loadBar.graphics.endFill();
        loadBar.x = 0;
        loadBar.y = 0;
        addChild(loadBar);

        //init handler, run when we have the big images content.
        function loadLargeInit(e:Event):void {
                //remove the loadProgress bar
                removeChild(loadBar);
                //add the large content to the stage or wherever
                //first remove any existing content (if any) in our large image container
                //if you wanted to do a cross fade, remove this if test, and run an oncomplete tween function for the
                //fade in that removes the bottom child (old image) from the largeContent clip.
                if (largeContent.numChildren>0) {
                        largeContent.removeChildAt(0);
                }
                //position the loaded content
                loader.content.x = 50;
                loader.content.y = 10;
                largeContent.addChild(loader.content);
                //set the big images alpha to 0, so we can fade it in
                largeContent.alpha = 0
                TweenLite.to(largeContent, 4, {alpha:1});//alpha in the large image
                //clear the loadText of its text
                load_txt.text = "";
                //add the about text to the output text area
                outPut_txt.htmlText ="";
                outPut_txt.htmlText = String(xmlData.pic.about[targetThumbs]);
        }
        //handle loading progress
        function loadLargeProgress(e:ProgressEvent):void {
                //trace("LOADED "+Math.floor(e.bytesLoaded / 1024)+ " OF "+Math.floor(e.bytesTotal/1024));
                load_txt.text = "LOADED "+Math.floor(e.bytesLoaded / 1024)+ " OF "+Math.floor(e.bytesTotal/1024);
                loadBar.width = (stage.stageWidth/100)*Math.floor(e.bytesLoaded/e.bytesTotal*100);
        }
}
//thumbnail rollOver and Off handlers

function offThumb(event:MouseEvent):void {
        TweenLite.to(event.target, 2, {alpha:1});//alpha in the thumbnails
}

function overThumb(event:MouseEvent):void {
        TweenLite.to(event.target, .3, {alpha:.2});//alpha out the thumbnails
}


Varnol 14.05.2008 14:36

Код:

/*********************************************************************
CONTENT CLEARING FUNCTION
**********************************************************************/
//Removes thumbnails, resets all vars related to thumbnails layout, and clears any large clips that may be present

function cleanOutThumbs():void{
        //first test to see if we have got any content in the scroller
        if(holder_mc.numChildren >0){
        while(holder_mc.numChildren >0){
                //check to see if we have a movieClip, if we do, it has the pictureValue prop, so lets null that
                //this will let the MC be garbage collected, if we remove all references to it
                if(holder_mc.getChildAt(0) as MovieClip){
                        MovieClip(holder_mc.getChildAt(0)).pictureValue = null
                        //remove the event Listeners attached to each thumb
                        holder_mc.getChildAt(0).removeEventListener(MouseEvent.MOUSE_OVER, overThumb);
                        holder_mc.getChildAt(0).removeEventListener(MouseEvent.MOUSE_OUT, offThumb);
                        holder_mc.getChildAt(0).removeEventListener(MouseEvent.CLICK, loadBigImage);
                        }
               
                holder_mc.removeChildAt(0)
        }
        //we are done in our loop, so lets remove the scrolling event listeners & reset the vars that control the layout of the scroll track
        //remove any large content that may be loaded. If we have large content, we probably have text, so kill that to       
        //Note, that the scroller track is constructed again with each thumbs load, so we don't actually need to totally kill that.
        if (largeContent.numChildren>0) {
                        largeContent.removeChildAt(0);
                        outPut_txt.htmlText ="";
                }
        p = 0
        pictureValue = 0
        changex = 0
        holder_mc.removeEventListener(MouseEvent.ROLL_OVER,startScroll);
        holder_mc.removeEventListener(MouseEvent.ROLL_OUT, stopScroll);
}
}


/*
**********************************************************************
SET UP A BASIC THUMBNAILS SCROLLER
**********************************************************************/

//define the scrollable area
var scrollPaneX:int;//populated in thumbs init load handler
var scrollPaneY:int;//populated in thumbs init load handler
var scrollPaneWidth:int;//populated in thumbs init load handler
var scrollPaneHeight:int;//populated in thumbs init load handler
var scrollTrackWidth:int;//populated in thumbs init load handler
//scroller variables
var scrollSpeed:int = 15;//scroll speed

//create a holder sprite to hold thumbnails we leave its width undefined here, as it will
//change depending on number of thumbnails
var holder_mc:Sprite = new Sprite();//thumbs load into
addChild(holder_mc);

var thumbMask_mc:Sprite = new Sprite();//mask for thumbs track
//thumbs track background clip. We create this to create a solid track
//as if we have padding, we have gaps, and our mouse events turn on off as the mouse moves
//over each thumb, which makes for jerky scrolling. This also means we can use native
//mouse events to turn on off the scrolling, rather than having an enterframe running all the time
var thumbTrackBg_mc:Sprite = new Sprite();

function constructScroller():void {
        //position thumbs scroller inline with pre set vars
        holder_mc.x=scrollPaneX;
        holder_mc.y = scrollPaneY;

        //create mask sprite
        thumbMask_mc.graphics.beginFill(0xFFFFFF);
        thumbMask_mc.graphics.drawRect(0, 0, scrollPaneWidth, scrollPaneHeight);
        thumbMask_mc.graphics.endFill();
        thumbMask_mc.x = scrollPaneX;
        thumbMask_mc.y = scrollPaneY;
        addChild(thumbMask_mc);

        //add the mask to the holder mc
        holder_mc.mask = thumbMask_mc;

        //add the scroll hit area mc
        thumbTrackBg_mc.graphics.beginFill(0xFFFFFF);
        thumbTrackBg_mc.graphics.drawRect(0, 0, scrollPaneWidth, scrollPaneHeight);
        thumbTrackBg_mc.graphics.endFill();
        thumbTrackBg_mc.alpha=0;
        thumbTrackBg_mc.x = 0;//relative to holder
        thumbTrackBg_mc.y = 0;//relative to holder
        thumbTrackBg_mc.width = scrollTrackWidth;
        thumbTrackBg_mc.height = scrollPaneHeight;

        holder_mc.addChildAt(thumbTrackBg_mc,0);
}
//function that simply adds the event listeners to our scroll track
//we call this when we have loaded in all the thumbs, as this stops a user from being
//able to scroll a half empty thumbnails track, which would look crap.
function addScrollListeners():void{
        holder_mc.addEventListener(MouseEvent.ROLL_OVER,startScroll);
        holder_mc.addEventListener(MouseEvent.ROLL_OUT, stopScroll);
}

//handlers that either add or delete the scroll enterframe event
function startScroll(e:MouseEvent):void{
        thumbMask_mc.addEventListener(Event.ENTER_FRAME, scrollThumbs);
}

function stopScroll(event:MouseEvent):void{
        thumbMask_mc.removeEventListener(Event.ENTER_FRAME, scrollThumbs);
}

//the scrollThumbs function
function scrollThumbs(event:Event):void {
        holder_mc.x += Math.cos((-thumbMask_mc.mouseX/scrollPaneWidth)*Math.PI)*scrollSpeed;
        if (holder_mc.x>scrollPaneX) {
                holder_mc.x = scrollPaneX;
        }
        if (-holder_mc.x>(holder_mc.width-scrollPaneWidth-scrollPaneX)) {
                holder_mc.x = -(holder_mc.width-scrollPaneWidth-scrollPaneX);
               
        }

}

/*********************************************************************
SET UP CSS TEXT STYLING FROM EXTERNAL CSS STYLE SHEET
**********************************************************************/

function loadCss(cssToLoad:String):void {
        var cssLoader:URLLoader = new URLLoader();
        cssLoader.addEventListener(Event.COMPLETE, cssCompleteListener);
        cssLoader.addEventListener(IOErrorEvent.IO_ERROR, cssLoadFail);
        cssLoader.load(new URLRequest(cssToLoad));
}

loadCss("styles.css");

function cssCompleteListener(e:Event):void {
        var styleSheet:StyleSheet = new StyleSheet();
        styleSheet.parseCSS(e.target.data);
        //style the textbox
        outPut_txt.styleSheet = styleSheet;
}

function cssLoadFail(event:IOErrorEvent):void {
        trace("Looks like there was an error loading the CSS file");
}
/*********************************************************************
BUTTONS FOR LOADING REMOVING CONTENT - DELETE THESE IF NEED BE
**********************************************************************/
//load new and remove all event handlers
load_mc.addEventListener(MouseEvent.CLICK,loadNew);
function loadNew(event:MouseEvent):void{
        cleanOutThumbs()
        loadXml("gallery2.xml");
}

Вроде бы вместо
loadXml("gallery2.xml");
надо написать что-то типа
loadXml(new URLRequest(String(xmlData.pic.next[p])));

но тупо "так" это не работает :o

etc 15.05.2008 23:20

Serg85 получает плюс за флейм.


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

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