Tải bản đầy đủ (.pdf) (29 trang)

thanhanlang Flash AS 30 Danh sach hien thi

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (425.58 KB, 29 trang )

<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>

1


DANH SÁCH HIỂN THỊ ( DISPLAY LIST )


Bạn muốn thêm một ñối tượng hiển thị mới vào danh sách hiển thị để nó xuất hiện trên màn
hình.( Nói cách khác là giả sử bạn muốn thêm một đối tượng nào đó hiển thị lên màn hình –
danh sách hiển thị được hiểu là tập hợp các ñối tượng ñược hiển thị.)


Sử dụng các Method addChild () và addChildAt () từ lớp DisplayObectContainer.


Các Flash Player gồm có hai phần chắnh có quan hệ về chức năng với nhau ựể tạo một ựơn
vị liên kết chặt chẽ.đó là ActionScript Virtual Machine (AVM-Máy ảo xử lý các Code) và
Rendering Engine( máy vẽ). AVM có trách nhiệm thực hiện các code ActionScript , và
Rendering Engine là những ựối tượng biểu diễn trên màn hình. Bởi vì Flash Player gồm có
hai phần chắnh nên biểu diễn ( vẽ ra) một ựối tượng trên màn hình là một q trình hai
bước:


• ðối tượng biểu diễn phải được tạo ra thơng qua cơ cấu của ActionScript ( tức là phải
dùng code để tạo )


• Sau đó đối tượng phải ñược vẽ trên màn hình nhờ Rendering Engine


Bước đầu được thực hiện bằng cách dùng tốn tử new() ñể tạo ra một instance của loại ñối
tượng cần thể hiện .ðối tượng nào muốn thêm vào danh sách hiển thị thì nó phải thuộc về
một subclass trực tiếp hoặc gián tiếp của lớp DisplayObject, như Sprite, MovieClip,
TextField, hoặc một lớp riêng do bạn tạo ra .Ví dụ để tạo ra một TextField bạn sẽ sử dụng
ñoạn code sau ñây:


var hello:TextField = new TextField( );


Các dòng mã này trước tiên tạo ra một ñối tượng hiển thị TextField trong AVM, tuy nhiên


nó khơng được hiển thị ngay trên màn hình vì đối tượng này khơng tồn tại trong


Rendering Engine. ðể tạo đối tượng trong Rendering Engine, ñối tượng cần phải ñược ñưa
vào cây danh sách hiển thị. ðiều này có thể ñược thực hiện bằng cách gọi phương thức
addChild () hoặc addChildAt () từ một instance ( như Sprite, MovieClip, TextField) của
lớp DisplayObjectContainer .Khi đó bản thân ñối tượng sẽ có ngay trong cây danh sách
hiển thị.( Và tất nhiên khi chạy chương trình Rendering Engine sẽ vẽ ngay đối tượng lên
màn hình )


Tóm lại : Dùng tốn tử new() để tạo đối tượng , sau đó dùng phương thức addChild() hay
addChildAt() để khởi động máy vẽ và vẽ lên màn hình.


addChild(child:flash.display:DisplayObject) — method, class
flash.display.DisplayObjectContainer


Thên một ñối tượng hiển thị con vào ñối tượng hiển thị cha (DisplayObjectContainer)
addChild(child:flash.display:DisplayObject) — method, class flash.display.Stage


addChildAt(child:flash.display:DisplayObject, index:int) method, class
flash.display.DisplayObjectContainer


</div>
<span class='text_page_counter'>(2)</span><div class='page_container' data-page=2>

2


addChildAt(child:flash.display:DisplayObject, index:int) — method, class
flash.display.Stage


Adds a child DisplayObject instance to this DisplayObjectContainer instance.


Phương thức addChild() cần một tham số là ñối tượng cần hiển thị , nó được thêm vào
containner ( thùng chứa : là ñối tượng cha ) như là một đối tượng con của container đó.


Ví dụ :


package {


import flash.display.DisplayObjectContainer;
import flash.display.Sprite;


import flash.text.TextField;


public class DisplayListExample extends Sprite {
public function DisplayListExample( ) {


// Tạo một ñối tượng cần hiển thị – là TextField
- nhờ ActionScript


var hello:TextField = new TextField( );
hello.text = "hello";




// Tạo ñối tượng trong rendering engine
// bằng cách thêm vào display list. Khi đó
textfield sẽ hiển thi




addChild( hello );// tham số là ñối tượng cần
hiển thị


}


}
}


Một ñối tượng hiển thị TextField ñược tạo ra trong hàm tạo DisplayListExample, hàm
tạoầnỳ cho phép tạo các ñối tượng bên trong AVM . Lúc này, ñối tượng sẽ khơng xuất hiện
trên màn hình bởi vì Rendering Engine khơng biết về nó cả. Chỉ sau khi đối tượng ñược
thêm vào list hiển thị thông qua lời gọi phương thức addChild () thì TextField mới ñược
ñược hiển thị.


Các phương thức addChild() và addChildAt() chỉ ñưa ñối tượng hiển thị con vào ñối tượng
hiển thị cha . Ta không cần thiết phải ñưa các ñối tượng hiển thị vào display list. ðối tượng
con chỉ ñưa vào chỉ khi ñối tượng cha cũng phải dược ñưa vào display list .


ðoạn code sau minh hoạ tại sao phương thức addChild() không bảo ñảm một ñối tượng
hiển thị ñược ñưa vào display list. Text ñược chứa trong một container nhưng bản thân
container chưa ñưa vào display list nên text sẽ khơng nhì thấy..


</div>
<span class='text_page_counter'>(3)</span><div class='page_container' data-page=3>

3


var hello:TextField = new TextField( );
hello.text = "hello";


// Tạo một container ñể chứa textField- ñây là một
Sprite


var container:Sprite = new Sprite( );
// Thêm textField vào container


container.addChild( hello );



ðể làm cho hiển thị văn bản trên màn hình, container chứa văn bản cũng cần phải ñược
thêm vào danh sách hiển thị. ðiều này ñược thực hiện bằng cách tham chiếu ñến một ñối
tượng container khác ñã có trên danh sách hiển thị, chẳng hạn như là _root ( container gốc )
hoặc stage ( màn hình trình diễn chính của file) Ta cũng sẽ dùng addChild (), và ñưa vào
root hay stage ñối tượng container của text hiển thị.


// Lấy root làm container và ñưa vào root


// container lưu giữ text từ đó làm nó xuất hiện trên
màn hình


DisplayObjectContainer( root ).addChild( container );


Các container chứa ñối tượng hiển thị có khả năng lưu giữ rất nhiều đối tượng con.
Container sẽ giữ bên trong một danh sách các ñối tượng con,và thứ tự của các ñối tượng
con này trong danh sách xác ñịnh thứ tự hiển thị trên màn hình. Mỗi đối tượng con sẽ có
một vị trí rõ ràng trong danh sách vì nó được gán bởi một giá trị chỉ mục là một số nguyên,
giống như một array vậy. Vị trí 0 là vị trí dưới cùng của danh sách và đối tượng ở vị trí 0 sẽ
được vẽ nằm dưới ( sau) đối tượng con ở vị trí 1, và nó ( vị trí 1) lại được vẽ nằm dưới
(sau) đối tượng ở vị trí 2… ðiều này tương tự khái niệm depth ( ñộ sâu) trong các bản flash
trước, nay nó dễ quản lý hơn .Khơng có kẻ hở nào giữa các số chỉ vị trí.ðiều này có nghĩa
là khơng bao giờ có đối tượng con nào khác ở vị trí 0 và 2 nếu vị trí 1 đã có.


Khi một đối tượng con được thêm vào qua phương thức addChild() thì nó sẽ ñược vẽ ngay
phí trên cùng của các ñối tượng con khác vì lệnh addChild() sẽ đặt đối tượng con phía trước
của danh sách các đối tượng stack ta dùng addChildAt().


Phương thức addChildAt() cần 2 tham số: (tham số ñầu chỉ ñối tượng cần thêm vào , và
tham số sau chỉ vị trí mà đối tượng con cần dùng) Việc định vị trí 0 làm cho ñối tượng con
ñược ñưa vào sẽ ở vị tí cuối của lít và làm cho nó xuất hiện phí dưới tất cả các đối tượng


con khác.Nếu có đối tượng con dang ở vị trí được chọn thì tất cả các đối tượng cọn tại đó và
trên ñvijcos chỉ số ñều ñược dich lên một ñơn vị , nhờ đó đối tượng con sẽ được chèn vào.
Nếu định vị trí khơng thích hợp , ví dụ vị trí có giá trị âm hay vị trí có giá trị cao hơn số các
ñối tượng con trong container sẽ tạo ra lỗi RangeError và làm cho ñối tượng con khơng
được đưa vào.


</div>
<span class='text_page_counter'>(4)</span><div class='page_container' data-page=4>

4


, vì nó được thêm vào sau các vịng trịn màu đỏ. Sau hai lần gọi phương thức addChild (),
vịng trịn màu đỏ sẽ ở vị trí 0 và vịng trịn màu xanh sẽ ở vị trí 1.Vịng trịn màu xanh lá
cây sau đó ñược chèn vào giữa hai vòng tròn bằng phương thức addChildAt () , xác ñịnh
cụ thể vị trí của nó là1 trong danh sách. Các vịng trịn màu xanh, trước đó tại vị trí 1, được
chuyển đến vị trí 2 và vịng trịn màu xanh lá cây được đưa vào vị trí số 1 . Kết quả cuối
cùng là vòng tròn màu đỏ ở vị trí 0 được vẽ bên dưới vịng trịn màu xanh lá cây ở các vị trí
1, và vịng trịn màu xanh lá cây được vẽ bên dưới vịng trịn màu xanh ở vị trí 2.


package {


import flash.display.*;


public class CircleExample extends Sprite {
public function CircleExample( ) {


// Create three different colored circles and
// change their coordinates so they are staggered
// and aren't all located at (0,0).


var red:Shape = createCircle( 0xFF0000, 10 );
red.x = 10;



red.y = 20;


var green:Shape = createCircle( 0x00FF00, 10 );
green.x = 15;


green.y = 25;


var blue:Shape = createCircle( 0x0000FF, 10 );
blue.x = 20;


blue.y = 20;


// First add the red circle, then add the blue
circle (so blue


// is drawn on top of red)
addChild( red );


addChild( blue );


// Place the green circle between the red and
blue circles


addChildAt( green, 1 );
}





// Helper function to create a circle shape with a
given color


// and radius


public function createCircle( color:uint,
radius:Number ):Shape {


var shape:Shape = new Shape( );
shape.graphics.beginFill( color );


shape.graphics.drawCircle( 0, 0, radius );
shape.graphics.endFill( );


return shape;
}


</div>
<span class='text_page_counter'>(5)</span><div class='page_container' data-page=5>

5
}


Cho đến nay chúng ta đã chỉ nói về việc thêm các mục mới vào danh sách hiển thị, nhưng
sẽ xảy ra gì khi addChild () ñược sử dụng trên một ñối tượng con ñã ñược vào danh sách
hiển thị, như một ñối tượng con của container khác? ðây là khái niệm về reparenting. ðối
tượng ñược lấy ra từ các container mà nó hiện đang ở và được đặt vào trong các container
khác (mà nó đang được thêm vào.)


Khi bạn reparent một đối tượng hiển thị, khơng cần loại bỏ nó trước tiên. Phương thức
addChild () sẽ lo điều đó.


Ví dụ: ( bạn xem kỷ code ñể biết ñạng reparent phần nào,


package {


import flash.display.*;


public class DisplayListExample extends Sprite {
public function DisplayListExample( ) {


// Create three different colored circles and
// change their coordinates so they are staggered
// and aren't all located at (0,0).


var red:Shape = createCircle( 0xFF0000, 10 );
red.x = 10;


red.y = 20;


var green:Shape = createCircle( 0x00FF00, 10 );
green.x = 15;


green.y = 25;


var blue:Shape = createCircle( 0x0000FF, 10 );
blue.x = 20;


blue.y = 20;


// Create a container to hold the three circles,
and add the



// circles to the container


var container1:Sprite = new Sprite( );
container1.addChild( red );


container1.addChild( green );
container1.addChild( blue );


// Add the container to the display list
addChild( container1 );




// Create a second container and add it the
display list


var container2:Sprite = new Sprite( );
addChild( container2 );




</div>
<span class='text_page_counter'>(6)</span><div class='page_container' data-page=6>

6


// which has the net effect of the red circle
being drawn


// on top of the green and blue ones.
container2.addChild( red );



}


// Helper function to create a circle shape with a
given color


// and radius


public function createCircle( color:uint,
radius:Number ):Shape {


var shape:Shape = new Shape( );
shape.graphics.beginFill( color );


shape.graphics.drawCircle( 0, 0, radius );
shape.graphics.endFill( );


return shape;
}


}
}


Loại bỏ một mục từ display list


Ta dùng các phương thức : removeChild( ) và removeChildAt( ) từ lớp
<i>DisplayObectContainer </i>


Phương thức removeChild( ) có một tham số chỉ đối tượng cần gở ra khỏi container. Nếu
đối tượng dó khơng phải là con của một container thì có lỗi ArgumentError được ném ra.


Ví dụ :


package {


import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;


public class RemoveChildExample extends Sprite {
// tạo một biến ñịa phương ñể lưu tham khảo ñến
textfield sẽ remove





private var _label:TextField;


public function RemoveChildExample( ) {
_label = new TextField( );


_label.text = "Some Text";


</div>
<span class='text_page_counter'>(7)</span><div class='page_container' data-page=7>

7


//Khi kích chuột vào stage thì label bị gở



stage.addEventListener( MouseEvent.CLICK,
removeLabel );


}


// Gở label từ displayl list


public function removeLabel( event:MouseEvent
):void {


removeChild( _label );
}


}
}


Ví dụ : dùng removeChildAt()
package {


import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;


public class DisplayListExample extends Sprite {


public function DisplayListExample( ) {
var label:TextField = new TextField( );
label.text = "Some Text";





addChild( label );


//Khi kích chuột vào stage thì label bị gở
stage.addEventListener( MouseEvent.CLICK,


removeLabel );
}




// Gở label từ display list


public function removeLabel( event:MouseEvent
):void {


// Only remove the label if it exists
if ( numChildren > 0 ) {


removeChildAt( 0 );
}


}
}
}


</div>
<span class='text_page_counter'>(8)</span><div class='page_container' data-page=8>

8


import flash.display.*;


public class DisplayObjectUtilities {
// Gở tát cả các Child từ container


public static function removeAllChildren(


container:DisplayObjectContainer ):void {


// Vì giá trị chỉ số của Child ln thay đổi sau mỗi
lần remove nên cần lưu giá trị gốc vào một biến để có
thể tính chính xác


var count:int = container.numChildren;


// Loop


for ( var i:int = 0; i < count; i++ ) {
container.removeChildAt( 0 );


}
}
}
}


Có thể dùng DisplayObjectUtilities.removeAllChildren( ) để xố tất cả các Child ,
phương thức này nằm ở phần package thêm vào <b>ascb.util.DisplayObjectUtilities </b>



Di chuyển các ñối tượng tới trước, lui sau ñối tượng khác


Sử dụng các phương thức setChildIndex( ) của lớp DisplayObectContainer ñể thay ñổi vị
trí của một ñối tượng cụ thể


Sử dụng getChildIndex( ) và getChildAt( ) ñể truy vấn giữa các ñối tượng con , từ đó sắp
chúng vào đúng vị trí.


Ví dụ :
package {


import flash.display.*;


public class SetChildIndexExample extends Sprite {
public function SetChildIndexExample( ) {


// Tạo 3 hình trịn màu red, green, blue


var red:Shape = createCircle( 0xFF0000, 10 );
red.x = 10;


red.y = 20;


var green:Shape = createCircle( 0x00FF00, 10 );
green.x = 15;


green.y = 25;


var blue:Shape = createCircle( 0x0000FF, 10 );


blue.x = 20;


blue.y = 20;


</div>
<span class='text_page_counter'>(9)</span><div class='page_container' data-page=9>

9
addChild( red );


addChild( green );
addChild( blue );


// dichuyển blue về dưới cùng
setChildIndex( blue, 0 );
}




// hàm vẽ đường trịn


public function createCircle( color:uint, radius:Number
):Shape {


var shape:Shape = new Shape( );
shape.graphics.beginFill( color );


shape.graphics.drawCircle( 0, 0, radius );
shape.graphics.endFill( );


return shape;


}


}
}


Thay đổi vị trí khi khơng biết rõ vị trí của từng đối tượng.


Ta dùng getChildIndex() ñể lấy vị trí của ñối tượng và dùng setChildIndex() ñể ñặt ñối
tượng.


Ví dụ :
package {


import flash.display.*;


public class GetChildIndexExample extends Sprite {
public function GetChildIndexExample( ) {


// Create two different sized circles


var green:Shape = createCircle( 0x00FF00, 10 );
green.x = 25;


green.y = 25;


var blue:Shape = createCircle( 0x0000FF, 20 );
blue.x = 25;


blue.y = 25;



// blue ở trước green
addChild( green );
addChild( blue );


// ðưa green về trước blue
.


setChildIndex( blue, getChildIndex( green ) );
}


</div>
<span class='text_page_counter'>(10)</span><div class='page_container' data-page=10>

10
// Vẽ đường trịn


public function createCircle( color:uint, radius:Number
):Shape {


var shape:Shape = new Shape( );
shape.graphics.beginFill( color );


shape.graphics.drawCircle( 0, 0, radius );
shape.graphics.endFill( );


return shape;
}


}
}
Ví dụ:



Ví dụ này dùng array để lưu trử màu và dùng loop ñể tạo ra nhiều hình trịn. Nếu kích vào
stage thì đường trịn ở sau cùng sẽ ñược ñưa lên trước.


package {


import flash.display.*;
import flash.events.*;


public class GetChildAtExample extends Sprite {
public function GetChildAtExample( ) {


// ðịnh nghĩa mảng các màu


var color:Array = [ 0xFF0000, 0x990000, 0x660000,
0x00FF00,


0x009900, 0x006600, 0x0000FF,
0x000099,


0x000066, 0xCCCCCC ];
/ Tạo 10 ñường tròn dùng loop


for ( var i:int = 0; i < 10; i++ ) {


var circle:Shape = createCircle( color[i], 10 );
circle.x = i;


circle.y = i + 10; // the + 10 adds padding from the
top





addChild( circle );
}




stage.addEventListener( MouseEvent.CLICK, updateDisplay
);


}


// chuyển đường trịn ở dưới lên trên cùng


public function updateDisplay( event:MouseEvent ):void {
// getChildAt(kinhdungf ñể lấy chỉ số ñối tượng ở vị trí
0 và đưa lên vị trí ñầu //nhờ setChildIndex() , lưu ý vị
trí ñầu là numChildren-1


setChildIndex( getChildAt(0), numChildren - 1 );
}




</div>
<span class='text_page_counter'>(11)</span><div class='page_container' data-page=11>

11


public function createCircle( color:uint, radius:Number
):Shape {



var shape:Shape = new Shape( );
shape.graphics.beginFill( color );


shape.graphics.drawCircle( 0, 0, radius );
shape.graphics.endFill( );


return shape;
}


}
}
Lưu ý :


ðể thuận lợi cho việc vẽ và tạo đường trịn ta có thể tạo một Custom Class tên là Circle.
Khi đó để tạo một đường trịn ta chỉ cần dùng tốn tử new ()


Sau ñây là 2 package, một package tạo ra một custom class tên Circle và một package sử
dụng lớp đó để tạo nên các đường trịn . Cũng có thể viết code trực tiếp lên file fla bằng
cách import Circle như ñối với AS 2.0


package {


import flash.display.Shape;


/* The Circle class is a custom visual class */
public class Circle extends Shape {





// Local variables to store the circle properties
private var _color:uint;


private var _radius:Number;


/*


* Constructor: called when a Circle is created. The
default


* color is black, and the default radius is 10.
*/


public function Circle( color:uint = 0x000000,
radius:Number = 10 ) {


// Save the color and radius values
_color = color;


_radius = radius;


// When the circle is created, automatically draw it
draw( );


}

/*



* Draws the circle based on the color and radius values
*/


</div>
<span class='text_page_counter'>(12)</span><div class='page_container' data-page=12>

12
graphics.beginFill( _color );


graphics.drawCircle( 0, 0, _radius );
graphics.endFill( );


}
}
}


package {


import flash.display.Sprite;


public class UsingCircleExample extends Sprite {
public function UsingCircleExample( ) {


// Create some circles with the Circle class and
// change their coordinates so they are staggered
// and aren't all located at (0,0).


var red:Circle = new Circle( 0xFF0000, 10 );
red.x = 10;


red.y = 20;


var green:Circle = new Circle( 0x00FF00, 10 );


green.x = 15;


green.y = 25;


var blue:Circle = new Circle( 0x0000FF, 10 );
blue.x = 20;


blue.y = 20;


// Add the circles to the display list
addChild( red );


addChild( green );
addChild( blue );
}


}
}


TẠO NÚT ðƠN GIẢN
Packageflash.display


Class public class SimpleButton


Các thuộc tính của lớp SimpleButton:
downState : DisplayObject


</div>
<span class='text_page_counter'>(13)</span><div class='page_container' data-page=13>

13
hitTestState : DisplayObject



overState : DisplayObject


soundTransform : flash.media:SoundTransform
trackAsMenu : Boolean


upState : DisplayObject
useHandCursor : Boolean


Vấn ñề


Bạn muốn tạo một nút tương tác cho phép người dùng bấm vào và thực hiện một hành
ñộng, chẳng hạn như gửi một form hoặc tính tốn một tổng số.


Giải pháp


Tạo ra một thể hiện của lớp SimpleButton và tạo các ñối tượng hiển thị như upState,
Downstate, overState , và hitTestState. Ngoài ra, cần tạo ra một subclass của


SimpleButton mô tả hành vi của nút.


Sử dụng các sự kiện click ñể gọi một phương thức bất cứ khi nào người dùng nhấn nút.
Thảo luận


Mơ hình danh sách hiển thị cung cấp một cách dễ dàng ñể tạo các nút thông qua lớp


SimpleButton. Lớp SimpleButton cho phép người dùng tương tác với màn hình hiển thị các
ñối tượng sử dụng con chuột , và làm cho bạn dễ dàng chọn tương tác thông qua các trạng
thái khác nhau của nút ( như ấn nút, ñưa chuột vào nút…) Các trạng thái của nút liệt kê sau
đây được xem như là các thuộc tính của lớp SimpleButton



upState


Là trạng thái chuột không ở trên nút.
overState


Là trạng thái khi chuột ở trên nút. Khi chuột rời nút thì nút trở về trạng thái upState


downState


</div>
<span class='text_page_counter'>(14)</span><div class='page_container' data-page=14>

14


Là trạng thái xảy ra khi chuột vào vùng giới hạn của nút. hitTestState khơng bao giờ thực
sự được hiển thị trên màn hình, nó chỉ được sử dụng cho mục đích theo dõi chuột.


Ví dụ :
package {


import flash.display.*;
import flash.events.*;


public class SimpleButtonDemo extends Sprite {
public function SimpleButtonDemo( ) {


// tạo một button và ñịnh vị nó trên màn hình
var button:SimpleButton = new SimpleButton( );
button.x = 20;


button.y = 20;



// Tạo các trạng thái của button


button.upState = createCircle( 0x00FF00, 15 );
button.overState = createCircle( 0xFFFFFF, 16 );
button.downState = createCircle( 0xCCCCCC, 15 );
button.hitTestState = button.upState;




// thêm vào các event listener ñẻ khi click vào nut thì
các action được thực hiện




button.addEventListener( MouseEvent.CLICK, handleClick
);




// Finally, add the button to the display list
addChild( button );


}


// Hàm vẽ đường trịn


private function createCircle( color:uint, radius:Number


):Shape {


var circle:Shape = new Shape( );


circle.graphics.lineStyle( 1, 0x000000 );
circle.graphics.beginFill( color );


circle.graphics.drawCircle( 0, 0, radius );
circle.graphics.endFill( );


return circle;
}





private function handleClick( event:MouseEvent ):void {
trace( "Mouse clicked on the button" );


</div>
<span class='text_page_counter'>(15)</span><div class='page_container' data-page=15>

15
}


}


Sau khi chạy khối mã này, một vòng tròn màu xanh lá cây xuất hiện . Khi bạn di chuyển
chuột qua vòng tròn màu xanh lá cây, 1 vòng tròn màu trắng hơi lớn hơn xuất hiện tựa như
một rollover. Khi bạn nhấp vào vịng trịn màu trắng, nó biến thành một vòng tròn màu xám
hơi nhỏ hơn. Hiệu ứng hình ảnh này được tạo ra bởi đối tượng nút của SimpleButton sẽ
thay ñổi trạng thái của nó tuỳ thuộc vào các hành động của chuột .



trạng thái hitTeststate có lẻ là trạng thái được quan tâm nhiều nhất trong số các trạng thái
của nut. Trong ñoạn code trên hitteststate ñược thiết lập như upState. ðây là điều thường
xảy ra nhất vì thơng thường ta quan tâm tới phạm vi nút xuất hiện cụ thể trên màn hình.
hitTestState có thể được thiết lập cho bất kỳ hiển thị nào khi bạn muốn kiểm sốt giới hạn
hoạt động của một nút. ðể tạo ra một diện tích lớn hơn cho các nút nhấn, hãy thử thay ñổi
các ñoạn mã trước ñây ñể thiết lập hitTestState :


button.hitTestState = createCircle( 0x000000, 50 );


đoạn mã sau ựây tạo ra một lớp RectangleButton mới. Lớp RectangleButton xác ựịnh một
hành vi kiểu ựặc biệt của SimpleButton .đó là tạo một hình chữ nhật màu xanh lá cây có
văn bản trên ựầu của nó


package {


import flash.display.*
import flash.text.*;


import flash.filters.DropShadowFilter;


public class RectangleButton extends SimpleButton {
// The text to appear on the button


private var _text:String;


// Save the width and height of the rectangle
private var _width:Number;


private var _height:Number;



public function RectangleButton( text:String,
width:Number, height:Number ) {


// Save the values to use them to create the button
states


_text = text;
_width = width;
_height = height;


// Create the button states based on width, height, and
text value


</div>
<span class='text_page_counter'>(16)</span><div class='page_container' data-page=16>

16
}




// Create the display object for the button's up state
private function createUpState( ):Sprite {


var sprite:Sprite = new Sprite( );


var background:Shape = createdColoredRectangle(
0x33FF66 );


var textField:TextField = createTextField( false );




sprite.addChild( background );
sprite.addChild( textField );
return sprite;


}


// Create the display object for the button's up state
private function createOverState( ):Sprite {


var sprite:Sprite = new Sprite( );


var background:Shape = createdColoredRectangle(
0x70FF94 );


var textField:TextField = createTextField( false );


sprite.addChild( background );
sprite.addChild( textField );
return sprite;


}


// Create the display object for the button's down state
private function createDownState( ):Sprite {



var sprite:Sprite = new Sprite( );


var background:Shape = createdColoredRectangle(
0xCCCCCC );


var textField:TextField = createTextField( true );


sprite.addChild( background );
sprite.addChild( textField );


return sprite;
}




// Create a rounded rectangle with a specific fill color
private function createdColoredRectangle( color:uint
):Shape {


var rect:Shape = new Shape( );


</div>
<span class='text_page_counter'>(17)</span><div class='page_container' data-page=17>

17


rect.graphics.beginFill( color );


rect.graphics.drawRoundRect( 0, 0, _width, _height, 15


);


rect.graphics.endFill( );


rect.filters = [ new DropShadowFilter( 2 ) ];
return rect;


}


// Create the text field to display the text of the
button


private function createTextField( downState:Boolean
):TextField {


var textField:TextField = new TextField( );
textField.text = _text;


textField.width = _width;


// Center the text horizontally


var format:TextFormat = new TextFormat( );
format.align = TextFormatAlign.CENTER;


textField.setTextFormat( format );



// Center the text vertically


textField.y = ( _height - textField.textHeight ) / 2;
textField.y -= 2; // Subtract 2 pixels to adjust for
offset




// The down state places the text down and to the right
// further than the other states


if ( downState ) {
textField.x += 1;
textField.y += 1;
}




return textField;
}


}
}


Vì tất cả các code cho phép tạo nút đều được đóng gói để có thể dùng lại . Do vậy có thể dễ
dàng tạo nhiều nút mà không mất nhiều cơng sức.


Ví dụ sau sử dụng lớp RectangleButton đã tạo ở trên ñể tạo nhiều nút khác:
package {



import flash.display.*;


public class SimpleButtonDemo extends Sprite {
public function SimpleButtonDemo( ) {


</div>
<span class='text_page_counter'>(18)</span><div class='page_container' data-page=18>

18


// Create three rectangular buttons with different text
and


// different sizes, and place them at various locations
within


// the movie


var button1:RectangleButton = new RectangleButton(
"Button 1", 60, 100 );


button1.x = 20;
button1.y = 20;


var button2:RectangleButton = new RectangleButton(
"Button 2", 80, 30 );


button2.x = 90;
button2.y = 20;



var button3:RectangleButton = new RectangleButton(
"Button 3", 100, 40 );


button3.x = 100;
button3.y = 60;


// Add the buttons to the display list so they appear
on-screen


addChild( button1 );
addChild( button2 );
addChild( button3 );
}


}
}


LOAD CÁC HÌNH ẢNH BÊN NGỒI KHI CHẠY CHƯƠNG TRÌNH


Dùng lớp Loader để load hình ảnh và hiển thị chúng lên màn hình.


Package flash.display


Class public class Loader


Các phương thức của lớp:


Loader() : Tạo một đối tượng loader để có thể nhúng các file swf hay hình ảnh.
close():void : huỷ phương thức load()



</div>
<span class='text_page_counter'>(19)</span><div class='page_container' data-page=19>

19


loadBytes(bytes:ByteArray, context:LoaderContext = null):void
unload():void


unloadAndStop(gc:Boolean = true):void


Có ba bước cơ bản để load một nội dung bên ngoài:
Tạo một instance của lớp Loader.


Thêm instance Loader đó vào danh sách hiển thị.
Gọi hàm load (URL)


Hàm load() cần một tham số . Nó cần một đối tượng URLRequest ñể ñịnh rõ URL của
<i>nguồn.Khi file fla và hình ảnh ở chung một folder thì URL là tên của file hình ảnh ( phải có </i>
đi, ví dụ: “hinh1.jpg “).


Ví dụ:


package {


import flash.display.*;


import flash.net.URLRequest;


public class LoaderExample extends Sprite {
public function LoaderExample( ) {


// 1. Tạo một instance của lớp Loader


var loader:Loader = new Loader( );


// 2. Thêm instance Loader ñó vào danh sách hiển thị.
addChild( loader );


// 3. Gọi hàm load (URL)


loader.load( new URLRequest( "image.jpg" ) );
}


}
}


Trong q trình load file có thể xảy ra lỗi. Lỗi có thể là do địa chỉ URL sai , hoặc do bảo
mật hoặc do dung lượng file quá lớn nên q trình tải bị chậm. Thay vì để màn hình trống
trong q trình tải ta có thể cho hình ảnh loading vào màn hình để thơng tin về tiến trình
loading


</div>
<span class='text_page_counter'>(20)</span><div class='page_container' data-page=20>

20
open : được tạo ra khi ñối tượng bắt ñầu load.


progress : ñược tạo khi tiến trình ñã và ñang thực hiện
complete : Khi tải xong


init : khi các thuộc tính và phương thức của file .swf được load tồn tại.


httpStatus : Tạo ra khi các mã trạng thái cho một yêu cầu HTTP bị lỗi được phát hiện
trong q trình cố gắng tải .


ioError : tạo ra khi có lỗi nặng



securityError tạo ra khi có lỗi về bảo mật
unload : tạo ra khi gọi phương trình unload()
Ví dụ:


package {


import flash.display.*;
import flash.text.*;


import flash.net.URLRequest;
import flash.events.*;


public class LoaderExample extends Sprite {
public function LoaderExample( ) {


// tạo một instance loader và thêm vào display list
var loader:Loader = new Loader( );


addChild( loader );


//thêm một event handlers để kiểm tra tiến trình


loader.contentLoaderInfo.addEventListener( Event.OPEN,
handleOpen );


loader.contentLoaderInfo.addEventListener(
ProgressEvent.PROGRESS, handleProgress );



loader.contentLoaderInfo.addEventListener(
Event.COMPLETE, handleComplete );




// Load vào một file hình ảnh.


loader.load( new URLRequest( "image.jpg" ) );
}




private function handleOpen( event:Event ):void {
trace( "open" );


}


private function handleProgress( event:ProgressEvent
):void {


var percent:Number = event.bytesLoaded /
event.bytesTotal * 100;


trace( "progress, percent = " + percent );
}




</div>
<span class='text_page_counter'>(21)</span><div class='page_container' data-page=21>

21


}


}
}


Bằng cách ñặt thêm code vào các event handler bạn có thể theo dõi tốt hơn các tiến trình khi
load.Ví dụ: ta thay đổi các code trong các event handler ở phần trên như sau:


private function handleOpen( event:Event ):void {


// Create a simple text-based preloader and add it to the
// display list


_loaderStatus = new TextField( );
addChild( loaderStatus );


_loaderStatus.text = "Loading: 0%";
}


private function handleProgress( event:ProgressEvent ):void {
// Update the loading % to inform the user of progress


var percent:Number = event.bytesLoaded / event.bytesTotal *
100;


_loaderStatus.text = "Loading: " + percent + "%";
}


private function handleComplete( event:Event ):void {
// Clean up - preloader is no longer necessary



removeChild( loaderStatus );
_loaderStatus = null;


}


TẢI VÀ TƯƠNG TÁC VỚI .SWF NGOÀI


Dùng lớp Loader để load file .swf nhờ vào thuộc tính content của instance Loader.
Ví dụ sau sẽ tạo ra 2 file .swf là ExternalMovie.swf và LoaderExample.swf. file


<i>ExternalMovie.swf sẽ ñược load trong khi chạy ,vào file thứ hai . Code cho file thư nhất: </i>
package {


import flash.display.Sprite;
import flash.display.Shape;


public class ExternalMovie extends Sprite {
private var _color:uint = 0x000000;


private var _circle:Shape;


public function ExternalMovie( ) {
updateDisplay( );


}


private function updateDisplay( ):void {



</div>
<span class='text_page_counter'>(22)</span><div class='page_container' data-page=22>

22


// and make it visible by adding it to the display list
if ( _circle == null ) {


_circle = new Shape( );
addChild( _circle );


}


// Clear any previously drawn content and draw
// a new circle with the fill color


_circle.graphics.clear( );


_circle.graphics.beginFill( _color );


_circle.graphics.drawCircle( 100, 100, 40 );
}




// Changes the color of the circle


public function setColor( color:uint ):void {
_color = color;


updateDisplay( );
}





// Gets the current circle color value
public function getColor( ):uint {
return _color;


}


}
}


Và code cho file thứ hai:
package {


import flash.display.*;


import flash.net.URLRequest;
import flash.events.Event;


public class LoaderExample extends Sprite {


private var _loader:Loader;


public function LoaderExample( ) {


// Create the Loader and add it to the display list


_loader = new Loader( );


addChild( _loader );


// Add the event handler to interact with the loaded
movie


</div>
<span class='text_page_counter'>(23)</span><div class='page_container' data-page=23>

23


// Load the external movie


_loader.load( new URLRequest( "ExternalMovie.swf" ) );
}




// Event handler called when the externally loaded movie
is


// ready to be interacted with


private function handleInit( event:Event ):void {
// Typed as * here because the type is not known at
compile-time.


var movie:* = _loader.content;



// Calls a method in the external movie to get data out
// Displays: 0


trace( movie.getColor( ) );


// Calls a method in the external movie to set data.
// Sets the color in the external movie, which draws
// a circle with the new color, in this case red
movie.setColor( 0xFF0000 );


}
}
}


TẠO TƯƠNG TÁC VỚI CHUỘT


sử dụng các event khác nhau của chuột ñể lắng nghe các tương tác của chuột lên ñối tượng
hiển thị loại InteractiveObject , dùng các thuộc tính chỉ đọc mouseX, mouseY từ


DisplayObject để kiểm tra vị trí của chuột so với ñối tượng hiển thị hoặc các thuộc tính
localX, localY từ mousEvent truyền cho sự kiện xử lý chuột.


Packageflash.display


Class public class InteractiveObject


ðây là một lớp trừu tượng cơ sở dành cho tất cả ccác ñối tượng hiển thị mà người dùng có
thể tương tác thơng qua chuột hay bàn phím. Lớp này có khá nhiều phương thức mô tả các
sự kiện khác nhau của chuột và bàn phím như



clear(),doubleClick,keyDown,mouseDown,mouseMove,mouseOver,mouseUp,mouseWheel
,rightClick, rightMouseDown,rightMouseUp,rollOver,rollOut,


Ví dụ sau tạo một hình trịn và sẽ xuất hiện 1 sự kiện( 1 dòng text ở output) khi chuột di
chuyển trên hình trịn


package {


import flash.display.Sprite;
import flash.events.*;


</div>
<span class='text_page_counter'>(24)</span><div class='page_container' data-page=24>

24


public class InteractiveMouseDemo extends Sprite {
public function InteractiveMouseDemo( ) {


var circle:Sprite = new Sprite( );
circle.x = 10;


circle.y = 10;


circle.graphics.beginFill( 0xFF0000 );
circle.graphics.drawCircle( 0, 0, 5 );
circle.graphics.endFill( );




circle.addEventListener( MouseEvent.MOUSE_MOVE,
handleMouseMove );



addChild( circle );
}




// Event handle to capture the move event over the circle
private function handleMouseMove( event:MouseEvent ):void
{


trace( "mouse move" );
}


}
}


Bằng cấu trúc circle.addEventListener() ta có thể đưa vào nhiều sự kiện khác
của chuột.


Có thể xác định toạ độ của chuột tương ñối( so với instance- toạ ñộ local) và tuyệt đối ( so
với màn hình- toạ độ global)như sau ñây ( thay hàm handleMouseMove ở trên bằng hàm
sau)


// Event handler to respond to a mouseMove event


private function handleMouseMove( event:MouseEvent ):void {
/* Displays:


local x: 3.95
local y: 3.45


*/


trace( "local x: " + event.localX );
trace( "local y: " + event.localY );


// Create the point that localToGlobal should convert
var localPoint:Point = new Point( event.localX,


event.localY );


// Convert from the local coordinates of the display object
that


// dispatched the event to the global stage coordinates
var globalPoint:Point = event.target.localToGlobal(
localPoint );


</div>
<span class='text_page_counter'>(25)</span><div class='page_container' data-page=25>

25
/* Displays:


global x: 13.95
global y: 13.45
*/


trace( "global x: " + globalPoint.x );
trace( "global y: " + globalPoint.y );
}


Sau ñây là một ví dụ về nhiều sự kiện. Khi chạy chương trình ta có thể dùng chuột để vẽ


hình trên màn hình.


package {


import flash.display.Sprite;
import flash.events.MouseEvent;


public class DrawingDemo extends Sprite {


// Flag to indicate whether the mouse is in draw mode
private var _drawing:Boolean;




public function DrawingDemo( ) {
// Configure the line style


graphics.lineStyle( 2, 0xFFCC33 );


// Drawing is false until the user presses the mouse
_drawing = false;




// Add the mouse listeners on the stage object to be
// notfied of any mouse event that happens while the
// mouse is over the entire movie



stage.addEventListener( MouseEvent.MOUSE_DOWN,
startDrawing );


stage.addEventListener( MouseEvent.MOUSE_MOVE, draw );
stage.addEventListener( MouseEvent.MOUSE_UP,


stopDrawing );
}




public function startDrawing( event:MouseEvent ):void {
// Move to the current mouse position to be ready for
drawing


graphics.moveTo( mouseX, mouseY );
_drawing = true;


}


public function draw( event:MouseEvent ):void {
if ( _drawing ) {


// Draw a line from the last mouse position to the
// current one


</div>
<span class='text_page_counter'>(26)</span><div class='page_container' data-page=26>

26
}



}


public function stopDrawing( event:MouseEvent ):void {
_drawing = false;


}

}
}


DRAG VÀ DROP


Các phương thức startDrop( ), stopDrag( ),drag( ) và drop( ) cho phép ta bắt ñầu kéo thả
chuột và tạo ra các đáp ứng cho sự kiện kéo thả đó, hay chỉ đơn thuần là kéo thả.


Ví dụ sau tạo ra 3 hình chữ nhật nhỏ có 3 màu và một hình chữ nhật lớn. Khi kéo một hình
chữ nhật nhỏ vào hình chữ nhật lớn thì hình chữ nhật lớn sẽ lấy màu của hình chữ nhật nhỏ.
package {


import flash.display.Sprite;


import flash.display.DisplayObject;
import flash.events.MouseEvent;
import flash.geom.Point;


import flash.filters.DropShadowFilter;
public class ColorDrop extends Sprite {



private var _red:Sprite;
private var _green:Sprite;
private var _blue:Sprite;
private var _white:Sprite;


// Saves the starting coordinates of a dragging Sprite so
// it can be placed back


private var startingLocation:Point;


// Create the rectangles that comprise the interface
// and wire the mouse events to make them interactive
public function ColorDrop( ) {


createRectangles( );
addEventListeners( );
}




private function createRectangles( ):void {
_red = new Sprite( );


</div>
<span class='text_page_counter'>(27)</span><div class='page_container' data-page=27>

27


_green = new Sprite( )



_green.graphics.beginFill( 0x00FF00 );
_green.graphics.drawRect( 0, 30, 10, 10 );
_green.graphics.endFill( );




_blue = new Sprite( );


_blue.graphics.beginFill( 0x0000FF );
_blue.graphics.drawRect( 0, 50, 10, 10 );
_blue.graphics.endFill( );




_white = new Sprite( );


_white.graphics.beginFill( 0xFFFFFF );


_white.graphics.drawRect( 20, 10, 50, 50 );
_white.graphics.endFill( );




addChild( _red );
addChild( _green );
addChild( _blue );
addChild( _white );
}





private function addEventListeners( ):void {


_red.addEventListener( MouseEvent.MOUSE_DOWN, pickup );
_red.addEventListener( MouseEvent.MOUSE_UP, place );


_green.addEventListener( MouseEvent.MOUSE_DOWN, pickup
);


_green.addEventListener( MouseEvent.MOUSE_UP, place );


_blue.addEventListener( MouseEvent.MOUSE_DOWN, pickup
);


_blue.addEventListener( MouseEvent.MOUSE_UP, place );
}




public function pickup( event:MouseEvent ):void {


// Save the original location so you can put the target
back


startingLocation = new Point( );
startingLocation.x = event.target.x;
startingLocation.y = event.target.y;



// Start dragging the Sprite that was clicked on and
apply


// a drop shadow filter to give it depth
event.target.startDrag( );


event.target.filters = [ new DropShadowFilter( ) ];


</div>
<span class='text_page_counter'>(28)</span><div class='page_container' data-page=28>

28


// it appears on top of everything else


setChildIndex( DisplayObject( event.target ),
numChildren - 1 );


}


public function place( event:MouseEvent ):void {


// Stop dragging the Sprite around and remove the depth
// effect (i.e., the drop shadow) from the filter


event.target.stopDrag( );
event.target.filters = null;


// Check to see if the Sprite was dropped over the


white


// rectangle, and if so, update the color
if ( event.target.dropTarget == _white ) {


// Determine which color was dropped, and apply that
color


// to the white rectangle
var color:uint;


switch ( event.target ) {


case _red: color = 0xFF0000; break;
case _green: color = 0x00FF00; break;
case _blue: color = 0x0000FF; break;
}




_white.graphics.clear( );


_white.graphics.beginFill( color );


_white.graphics.drawRect( 20, 10, 50, 50 );
_white.graphics.endFill( );


}



// Place the dragging Sprite back to its original
location


event.target.x = startingLocation.x;
event.target.y = startingLocation.y;
}



}
}


---////


</div>
<span class='text_page_counter'>(29)</span><div class='page_container' data-page=29></div>

<!--links-->

×