Как динамически добавлять объекты изображения на дисплей и затем взаимодействовать с ними? - PullRequest
3 голосов
/ 13 января 2010

Ниже приведен пример кода из модуля, который есть в моем приложении Flex. Я хочу динамически создавать объекты mx.controls.Image и добавлять их на экран. Я хочу, чтобы пользователь мог перемещать их (это работает, как показано ниже) и иметь возможность изменять свой z-индекс, а также записывать новые координаты X и Y после возвращения в базу данных. Как определить, с каким объектом в this.getChildren () является «выбранный» элемент, с которым работает пользователь? Например, когда я добавляю событие MOUSE_OVER, оно не работает.

<?xml version="1.0" encoding="utf-8"?>

        import flash.display.DisplayObject;
        import flash.events.MouseEvent;
        import mx.controls.Image;

        public var draggedObject:DisplayObject;
        public var selectedObject:DisplayObject;
        public var offsetX:Number;
        public var offsetY:Number;


        public function Add():void
        {
            var _image:Image = new Image;
            _image.source = "myimage.png";
            _imagem.x = 100;
            _image.y = 100;
            _image.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
            _image.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
            this.addChild(_image);
        }

        // This function is called when the mouse button is pressed.
        public function startDragging(event:MouseEvent):void
        {
            // remember which object is being dragged
            draggedObject = DisplayObject(event.target);
            selectedObject = draggedObject;

            // Record the difference (offset) between where the cursor was when
            // the mouse button was pressed and the x, y coordinate of the
            // dragged object when the mouse button was pressed.
            offsetX = event.stageX - draggedObject.x;
            offsetY = event.stageY - draggedObject.y;

            // move the selected object to the top of the display list
            //stage.addChild(draggedObject);

            // Tell Flash Player to start listening for the mouseMove event.
            stage.addEventListener(MouseEvent.MOUSE_MOVE, dragObject);                  
        }

        // This function is called when the mouse button is released.
        public function stopDragging(event:MouseEvent):void
        {
            // Tell Flash Player to stop listening for the mouseMove event.
            stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragObject);
        }

        // This function is called every time the mouse moves,
        // as long as the mouse button is pressed down.
        public function dragObject(event:MouseEvent):void
        {
            // Move the dragged object to the location of the cursor, maintaining 
            // the offset between the cursor's location and the location 
            // of the dragged object.
            draggedObject.x = event.stageX - offsetX;
            draggedObject.y = event.stageY - offsetY;

            // Instruct Flash Player to refresh the screen after this event.
            event.updateAfterEvent();
        }
    ]]>
</mx:Script>
<mx:Button x="83" y="93" label="New Image" click="this.Add()"/>
<mx:Label x="83" y="138" id="label1"/>
<mx:Label x="83" y="164" id="label2"/>

1 Ответ

4 голосов
/ 13 января 2010
  1. Используйте метод startDrag и stopDrag для объекта DisplayObject, вы избежите сделать это самостоятельно
  2. numChildren даст вамколичество дочерних элементов в списке отображения
  3. getChildIndex даст вам индекс объекта в списке отображения
  4. setChildIndex / swapChildren может использоваться для преобразования "z-index" в список отображения

Таким образом, смешивая эти различные функции, вы можете получить:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
    import mx.controls.Image;

    private function addImage() : void {
        var img : Image = new Image();
        img.source = imgClass;
        img.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown, false, 0, true);
        canvas.addChild(img);
    }

    private function onMouseUp(e : MouseEvent) : void {
        var img : Image = e.currentTarget as Image;
        if (img !== null) {
            stopDrag();
            img.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
        }
    }

    private function onMouseDown(e : MouseEvent) : void {
        var img : Image = e.currentTarget as Image;
        if (img !== null) {
            var parent : DisplayObjectContainer = img.parent;

           // get the index of the image and do what you want with it
            var idxImg : int = parent.getChildIndex(img);

           // put the clicked object on top of the list
            parent.setChildIndex(img, parent.numChildren - 1);

            img.addEventListener(MouseEvent.MOUSE_UP, onMouseUp, false, 0, true);
            img.startDrag();
        }
    }

    [Embed(source="assets/logo.png")]
    private var imgClass : Class;
]]>
</mx:Script>
<mx:Canvas id="canvas">
    <mx:Button label="add" click="addImage()"></mx:Button>
</mx:Canvas>
</mx:Application>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...