Flex手机项目 - 是内容适应舞台尺寸,方向
作者:hangge | 2014-12-29 14:55
由于不同的adroid,iphone设置的分辨率不同,Flex开发的移动应用如果要做到界面自适应可以进行如下操作:

1,如果应用支持手机横屏,纵屏的切换。则需要监听Event.ADDED_TO_STAGE以及StageOrientationEvent.ORIENTATION_CHANGE事件,当屏幕发生旋转的时候会触发该事件。
2,然后比较stageObj.stageWidth与stageObj.stageHeight的值即可判断出是横屏还是纵屏来设置currentState,同时界面上的组件布局使用Group,更具不同的state来设置是横向布局还是纵向布局。
下面是一个简单的例子:

代码如下:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
actionBarVisible="false"
creationComplete="onCreationComplete()"
tabBarVisible="false"
title="Home">
<fx:Declarations>
<s:State name="portrait" />
<s:State name="landscape" />
</fx:Declarations>
<fx:Script>
<![CDATA[
private static const BLUE:int = 0x3399FF;
private static const GREEN:int = 0x99CC00;
private static const RED:int = 0xFF3333;
private static const YELLOW:int = 0xFFCC00;
private function onCreationComplete():void
{
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
private function onAddedToStage(e:Event):void
{
stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE, onOrientationChange);
sizeComponents(systemManager.screen.width, systemManager.screen.height);
}
public function onOrientationChange(e:StageOrientationEvent):void
{
sizeComponents(systemManager.screen.width, systemManager.screen.height);
}
protected function sizeComponents(stageWidth:int, stageHeight:int):void
{
if(stageWidth < stageHeight)
{
currentState = "portrait";
a.width = stageWidth/2;
a.height = 1/3 * stageHeight;
b.width = stageWidth/2;
b.height = 1/3 * stageHeight;
c.width = stageWidth;
c.height = stageHeight - (1/3 * stageHeight) - (1/6 * stageHeight);
d.width = stageWidth;
d.height = 1/6 * stageHeight;
} else if(stageWidth > stageHeight) {
currentState = "landscape";
a.width = stageWidth/2;
a.height = stageHeight/2 - (1/6 * stageHeight)/2;
b.width = stageWidth/2;
b.height = stageHeight/2 - (1/6 * stageHeight)/2;
c.width = stageWidth/2;
c.height = stageHeight - (1/6 * stageHeight);
d.width = stageWidth;
d.height = 1/6 * stageHeight;
}
}
]]>
</fx:Script>
<s:Group>
<s:layout.portrait>
<s:VerticalLayout gap="0" />
</s:layout.portrait>
<s:layout.landscape>
<s:VerticalLayout gap="0" />
</s:layout.landscape>
<s:Group>
<s:layout.portrait>
<s:VerticalLayout gap="0" />
</s:layout.portrait>
<s:layout.landscape>
<s:HorizontalLayout gap="0" />
</s:layout.landscape>
<s:Group>
<s:layout.landscape>
<s:VerticalLayout gap="0" />
</s:layout.landscape>
<s:layout.portrait>
<s:HorizontalLayout gap="0" />
</s:layout.portrait>
<s:Graphic>
<s:Rect id="a">
<s:fill>
<s:SolidColor color="{BLUE}"/>
</s:fill>
</s:Rect>
</s:Graphic>
<s:Graphic>
<s:Rect id="b">
<s:fill>
<s:SolidColor color="{GREEN}"/>
</s:fill>
</s:Rect>
</s:Graphic>
</s:Group>
<s:Graphic>
<s:Rect id="c">
<s:fill>
<s:SolidColor color="{YELLOW}"/>
</s:fill>
</s:Rect>
</s:Graphic>
</s:Group>
<s:Graphic>
<s:Rect id="d">
<s:fill>
<s:SolidColor color="{RED}"/>
</s:fill>
</s:Rect>
</s:Graphic>
</s:Group>
</s:View>
全部评论(0)