---
title: "flex4 杂项"
author: "demojava"
date: "2011-12-21T17:00:52Z"
tags: []
categories: ["Web前端"]
slug: "flex4"
draft: false
lastmod: "2012-01-14T16:49:52Z"
id: 1195362
url: "https://demojava.iteye.com/blog/1195362"
---

**1. &lt;fx:Definition&gt; 标签（由编译器实现的）**  
可以在一个 &lt;fx:Library&gt; 标签内使用一个或多个 &lt;fx:Definition&gt; 标签定义图形子对象，然后可以将子对象用于应用程序的其它部分中。  
&lt;fx:Library&gt; 标签可以有任何数量的 &lt;fx:Definition&gt; 标签作为子对象。  
在作为 &lt;fx:Library&gt; 标签外部的标签添加 &lt;fx:Definition&gt; 标签之前，后一个标签中的元素不会被实例化或添加到显示列表。  
&lt;fx:Component&gt; 标签的语法如下：  
    &lt;fx:Library&gt;  
        &lt;fx:Definition name=defName&gt;  
            &lt;!-- Graphical children. --&gt;  
        &lt;/fx:Definition&gt;  
        ...  
        &lt;fx:Definition name=defName&gt;  
            &lt;!-- Graphical children. --&gt;  
        &lt;/fx:Definition&gt;  
    &lt;/fx:Library&gt;  
&lt;fx:Definition&gt; 标签必须定义 name 属性。在实例化该元素时，将使用该属性作为标签名。

```
<?xml version="1.0" encoding="utf-8"?> 
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
        xmlns:mx="library://ns.adobe.com/flex/mx" 
        xmlns:s="library://ns.adobe.com/flex/spark"> 
         <fx:Library> 
              <fx:Definition name="MySquare"> 
                   <s:Group> 
                        <s:Rect width="100%" height="100%"> 
                             <s:stroke> 
                                  <s:SolidColorStroke color="red"/> 
                             </s:stroke> 
                        </s:Rect> 
                   </s:Group> 
              </fx:Definition> 
              <fx:Definition name="MyCircle"> 
                   <s:Group> 
                        <s:Ellipse width="100%" height="100%"> 
                             <s:stroke> 
                                  <s:SolidColorStroke color="blue"/> 
                             </s:stroke> 
                        </s:Ellipse> 
                   </s:Group> 
              </fx:Definition> 
         </fx:Library> 
         <mx:Canvas> 
              <fx:MySquare x="0" y="0" height="20" width="20"/> 
              <fx:MySquare x="25" y="0" height="20" width="20"/> 
              <fx:MyCircle x="50" y="0" height="20" width="20"/> 
              <fx:MyCircle x="0" y="25" height="20" width="20"/> 
              <fx:MySquare x="25" y="25" height="20" width="20"/> 
              <fx:MySquare x="50" y="25" height="20" width="20"/> 
              <fx:MyCircle x="0" y="50" height="20" width="20"/> 
              <fx:MyCircle x="25" y="50" height="20" width="20"/> 
              <fx:MySquare x="50" y="50" height="20" width="20"/> 
         </mx:Canvas> 
    </s:Application>
<fx:Library>
```

**2.RichText**

RichText 是可以显示一行或多行富文本或嵌入图像的低级 UIComponent。  
由于性能原因，它不支持滚动、选择、编辑、可单击的超链接或从 URL 加载的图像。如果需要这些功能，请参阅 RichEditableText 类。

RichText 使用 Text Layout Framework (TLF) 库，而该库又基于 Flash Player 10 中的 Flash 文本引擎 (FTE)。组合后，  
它们可以提供使用高质量国际印刷效果的富文本布局。

Spark 体系结构提供三个文本“原型”- Label、RichText 和 RichEditableText。  
Label 运行速度最快且占用内存最少，因为它仅使用 FTE，没有 TLF，但其功能有限：无富文本、不可滚动、不可选择、不可编辑。  
RichText 新增了使用复杂布局显示富文本的功能，但仍然完全是非交互式的。  
RichEditableText 占用内存最多，但是提供 TLF 可以执行的大部分功能。您应该使用能够满足需求且占用最小内存的文本原型。  
RichText 与 MX 控件 mx.controls.Text 相似。Text 控件使用旧版 TextField 类（而不是 TLF）来显示文本。  
RichText 和 Text 之间最重要的区别是：  
与 Text 相比，RichText 可提供更佳的印刷效果和文本布局，且能更好地支持各国语言。  
RichText 拥有所显示内容的面向对象模型版本，而 Text 没有。  
Text 是可选择的，但 RichText 不支持选择操作。  
RichText 使用 TLF 面向对象模型的富文本，其中，诸如分段、段落、跨距和图像等文本布局元素在运行时由 ActionScript 对象表示，  
可以通过编程方式访问和操纵该对象。TLF 中用于表示富文本的中心对象是 TextFlow，  
因此可以通过将 RichText 的 textFlow 属性设置为 TextFlow 实例，来指定应显示的相应 RichText。  
（有关如何创建 TextFlow 的信息，请参阅 textFlow 属性的描述。）  
还可以设置从 TextBase 继承的 text 属性，但是如果不需要 TextFlow 的各种格式，应考虑改用 Label。

RichText中html标签:

&lt;s:div&gt; DivElement  
&lt;s:p&gt; ParagraphElement  
&lt;s:span&gt; SpanElement  
&lt;s:a&gt; LinkElement  
&lt;s:img&gt; InlineGraphicElement  
&lt;s:br&gt; BreakElement  
&lt;s:tab&gt; TabElement  
&lt;s:tcy&gt; TCYElement

**3.Group**

Group 类是可视元素的容器基类。Group 容器将实现 IUIComponent 接口的任何组件和实现 IGraphicElement 接口的任何组件视为子代。希望管理可视子项（可视组件和图形组件）时，使用此容器。  
为了改进性能和最小化应用程序大小，不能设置 Group 容器的外观。如果希望应用外观，请改用 SkinnableContainer。

注意：当 Group 内部存在 DisplayObject 子代（如组件或另一个 Group）时，刻度网格可能无法正常工作。如果子代是 GraphicElement 对象，并且全部共享该 Group 的 DisplayObject，则刻度网格将正常工作。

对 GraphicElement 子代设置下列任何属性要求 GraphicElement 创建其自己的 DisplayObject，从而使 Group 的刻度网格属性无效。

![](http://dl.iteye.com/upload/attachment/569834/bab94f78-49b4-3e46-8ada-0d6f549974bc.png)

```
<?xml version="1.0"?>
<!-- Simple example to demonstrate the Spark Group component. -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" >
	
	<s:Panel title="Group Component Example"
			 width="75%" height="75%" 
			 horizontalCenter="0" verticalCenter="0"> 
		<s:VGroup left="10" right="10" top="10" bottom="10">
			<s:Group>
				<!-- use a vertical layout with a 1 pixel gap between items -->
				<s:layout>
					<s:VerticalLayout gap="1" />
				</s:layout>
				
				<s:Label text="Group with a vertical layout" />
				<s:Rect width="150" height="20">
					<s:fill>
						<s:SolidColor color="0xE3E3E3" />
					</s:fill>
				</s:Rect>
				<s:Rect width="150" height="20">
					<s:fill>
						<s:SolidColor color="0xCCCCCC" />
					</s:fill>
				</s:Rect>
				<s:Rect width="150" height="20">
					<s:fill>
						<s:SolidColor color="0x888888" />
					</s:fill>
				</s:Rect>
			</s:Group>
			
			<mx:Spacer height="20" />
			
			<s:Group>
				<!-- use a horizontal layout with a 1 pixel gap between items -->
				<s:layout>
					<s:HorizontalLayout gap="1" />
				</s:layout>
				
				<s:Label text="Group with a horizontal layout" />
				<s:Rect width="25" height="25">
					<s:fill>
						<s:SolidColor color="0xE3E3E3" />
					</s:fill>
				</s:Rect>
				<s:Rect width="25" height="25">
					<s:fill>
						<s:SolidColor color="0xCCCCCC" />
					</s:fill>
				</s:Rect>
				<s:Rect width="25" height="25">
					<s:fill>
						<s:SolidColor color="0x888888" />
					</s:fill>
				</s:Rect>
			</s:Group>
			
			<mx:Spacer height="20" />
			
			<s:Group width="150" height="100">
				<!-- use the default basic layout where items are absolutely positioned -->
				
				<!-- add a background rectangle to stretch to fit the group -->
				<s:Rect top="0" left="0" right="0" bottom="0">
					<s:fill>
						<s:SolidColor color="0xCCCCCC" />
					</s:fill>
				</s:Rect>
				
				<s:Label x="0" y="0" text="Group with a basic layout" />
				<s:Rect x="20" y="20" width="30" height="25">
					<s:fill>
						<s:SolidColor color="0xE3E3E3" />
					</s:fill>
				</s:Rect>
				<s:Rect x="40" y="40" width="30" height="30">
					<s:fill>
						<s:SolidColor color="0x888888" />
					</s:fill>
				</s:Rect>
				<s:Rect x="60" y="60" width="30" height="30">
					<s:fill>
						<s:SolidColor color="0xBBBBBB" />
					</s:fill>
				</s:Rect>
			</s:Group>
		</s:VGroup>
	</s:Panel>
	
</s:Application>
```

**4.BorderContainer(可以有背景的group)**

BorderContainer 类定义一组 CSS 样式，用于控制容器的边框外观和背景填充。  
注意：因为使用 CSS 样式和类属性控制 BorderContainer 的外观，所以通常不会为该容器创建自定义外观。如果确实创建了自定义外观，外观类应当应用任何样式控制容器外观。  
默认情况下，边框的笔触是圆形的。如果不喜欢圆角，请将笔触的 joints 属性设置为 JointStyle.MITER。  
BorderContainer 容器具有下列默认特征：  
特征 说明  
默认大小 112 个像素宽 × 112 个像素高  
最小大小 112 个像素宽 × 112 个像素高  
最大大小 10000 个像素宽 × 10000 个像素高  
默认外观类 spark.skins.spark.BorderContainerSkin

![](http://dl.iteye.com/upload/attachment/569838/15c3062d-93cb-3fe9-9f25-ca7ed9c8017a.png)

```
<s:BorderContainer width="378" borderColor="#000000" borderWeight="4">
			<s:backgroundFill>
				<s:RadialGradient>
					<s:entries>
						<s:GradientEntry color="#FFFFFF"/>
						<s:GradientEntry color="#999999"/>
					</s:entries>
				</s:RadialGradient>
			</s:backgroundFill>
			<s:Label text="A BorderContainer with a backgroundFill object"
					 fontSize="14" fontWeight="bold"
					 horizontalCenter="0" verticalCenter="0"/>
		</s:BorderContainer>
```

**--flex 4改变容器的层次关系:**  
**1.使用setElementIndex改变**

```
<fx:Script>  
		<![CDATA[  
		import mx.core.IVisualElement;  
		protected function handler(event:Event):void  
		{  
			this.setElementIndex(event.currentTarget as IVisualElement,this.numElements-1);  
//this.swapElements(demo1,demo2);等上面代码
		}  
		]]>  
	</fx:Script>  
	<s:Panel id="demo1" title="demo1"  width="244" height="215" color="red" click="handler(event)">
	</s:Panel>
	<s:Panel  id="demo2" title="demo2"  width="244" height="215" x="134" y="45" color="green"  click="handler(event)" />
```

**2.改变元素的 depth 方法（必须是一组组件）**

```
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
	   xmlns:s="library://ns.adobe.com/flex/spark"
	   xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
	import mx.core.IVisualElement;
	import spark.components.supportClasses.GroupBase;
	private var currentIndex:int = 0;
	private function swapDepths():void
	{
		var layoutTarget:GroupBase = bLayout.target;
		var element:IVisualElement;
		for( var i:int = 0; i < layoutTarget.numElements; i++ )
		{
			element = layoutTarget.getElementAt( i ) as IVisualElement;
			if( i == currentIndex )
			{
				element.depth = layoutTarget.numElements - 1;
			}
			else if( i > currentIndex )
			{
				element.depth = i - 1;
			}
		}
		if( ++currentIndex > layoutTarget.numElements - 1 )
			currentIndex = 0;
	}
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout />
</s:layout>
<s:Group>
<s:layout>
	<s:BasicLayout id="bLayout" />
</s:layout>
<s:Button x="0" label="(1) button" />
<s:Button x="30" label="(2) button" />
<s:Button x="90" label="(3) button" />
</s:Group>
<s:Button label="swapDepths" click="swapDepths();" />
</s:Application>
```

**--Matrix3D 使用**

```
<fx:Script>
		<![CDATA[
			import mx.core.UIComponent;
			[Bindable] private var rot:Number = 90;
			private function rotate():void
			{
				var matrix:Matrix3D = button.getLayoutMatrix3D();
				matrix.appendRotation( 90, Vector3D.Z_AXIS );
				button.layoutMatrix3D = matrix;
				rot += 90;
			}
		]]>
	</fx:Script>
	<s:Group>
		<s:Group width="120">
			<s:layout>
				<s:VerticalLayout paddingLeft="5" paddingRight="5"
								  paddingTop="5" paddingBottom="5" />
			</s:layout>
			<s:Button id="button" label="push over" click="rotate();" />
		</s:Group>
	</s:Group>
```

**--Rotate3D 使用**

```
<fx:Declarations>
		<s:Rotate3D id="rotator1" autoCenterTransform="true" target="{btn1}"
					angleXFrom="0" angleXTo="360" />
		<s:Rotate3D id="rotator2" autoCenterTransform="true" target="{btn2}"
					angleYFrom="360" angleYTo="0" />
	</fx:Declarations>
	<s:Group width="300" height="300">
		<s:Group width="100%" height="100%">
			<s:layout>
				<s:VerticalLayout paddingLeft="5" paddingRight="5"
								  paddingTop="5" paddingBottom="5"
								  horizontalAlign="center" />
			</s:layout>
			<s:Button id="btn1" label="(0) button" click="{rotator1.play();}" />
			<s:Button id="btn2" label="(1) button" click="{rotator2.play();}" />
		</s:Group>
		<s:Rect width="100%" height="100%">
			<s:stroke>
				<mx:SolidColorStroke color="#000000" />
			</s:stroke>
		</s:Rect>
	</s:Group>
```

 

```
<fx:Script>
		<![CDATA[
			import flash.text.engine.TextLine;
			import flashx.textLayout.compose.IFlowComposer;
			import flashx.textLayout.compose.TextFlowLine;
			import flashx.textLayout.edit.SelectionState;
			import flashx.textLayout.events.SelectionEvent;
			[Bindable]
			private var bitmapData:BitmapData;
			private function selectionChanged(event:SelectionEvent):void {
				if(event.selectionState) {
					var state:SelectionState = event.selectionState;
					var composer:IFlowComposer =
						textAreaInst.textFlow.flowComposer;
					var tfline:TextFlowLine =
						composer.findLineAtPosition(state.anchorPosition);
					var tline:TextLine = tfline.getTextLine();
					if(tline) {
						var rect:Rectangle =
							tline.getAtomBounds(state.absoluteStart -
								tfline.absoluteStart);
						bitmapData = new
							BitmapData(tline.textBlock.baselineFontSize+ 33,
								tline.textBlock.baselineFontSize + 33, false,
								0xf6f6f6);
						var scaleMatrix:Matrix = new Matrix(0.9, 0, 0, 1,1 * rect.x *-1,rect.y *-1);
						bitmapData.draw(tline, scaleMatrix);
						img.source = bitmapData;
					}
				}
			}
		]]>
	</fx:Script>
	<s:BitmapImage id="img" width="200" height="200" source="{bitmapData}"/>
	<s:TextArea id="textAreaInst" fontSize="16">
		<s:textFlow>
			<s:TextFlow selectionChange="selectionChanged(event)">
				<s:p>
					<s:span>
						The TextFlow class is responsible for managing all the text
						content of a story.
					</s:span>
					<s:span>
						In TextLayout, text is stored in a hierarchical tree of
						elements.
					</s:span>
				</s:p>
			</s:TextFlow>
		</s:textFlow>
	</s:TextArea>
```

**--flex4 State 使用**

```
<s:states>
		<s:State name="normal" />
		<s:State name="author" />
	</s:states>
	<mx:Image id="imageHolder" width="140" height="140"
			  horizontalAlign="center" verticalAlign="middle"
			  source="@Embed(source='1.png')"
			  source.normal="@Embed(source='1.png')"
			  source.author="@Embed(source='111.png')"/>
	<s:Button id="selectorBtn" width="140"
			  label="Show Mike"
			  label.author="Show FlashGen"
			  click="currentState='author'"
			  click.author="currentState=''"/>

<s:states>
		<s:State name="normal" />
		<s:State name="state1" />
		<s:State name="state2" />
		<s:State name="state3" />
		<s:State name="state4" />
		<s:State name="state5" />
	</s:states>
	<s:Button id="btn1" label="Button 1"
			  includeIn="normal, state1, state2, state4"/>
	<s:Button id="btn2" label="Button 12121"
			  excludeFrom="normal, state3"/>
	<s:Button id="btn3" label="Button 3"
			  includeIn="normal, state3, state5"/>
	<s:ComboBox id="cBox"
				dataProvider="{new ArrayCollection([{label:'normal'}, {label:'state1'}, {label:'state2'}, {label:'state3'}, {label:'state4'},{label:'state5'}])}"
				selectedIndex="0"
				change="currentState = cBox.selectedItem.label"/>
```