Increase height of reflected object - actionscript-3

Want to reflect an image, and my code looks like
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
height="500" width="500"
creationComplete="init(event)">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import flash.filters.BlurFilter;
import mx.core.UIComponent;
import mx.events.FlexEvent;
private var loader:Loader = new Loader();
private var picture:BitmapData;
private var reflection:BitmapData;
private var reflectionHolder:Bitmap;
protected function init(event:FlexEvent):void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest("assets/rectangle.png"));
}
private function onComplete (event:Event):void
{
trace("loaded!");
var loaderInfo:LoaderInfo = LoaderInfo(event.target);
picture = new BitmapData(loaderInfo.width, loaderInfo.height, false, 0xFFFFFF);
picture.draw(loaderInfo.loader);
img.source=picture;
trace(picture.height,picture.width);
}
private function createReflection():void
{
reflection=new BitmapData(picture.width,picture.height,true,0x00ffffff);
var flipMatrix:Matrix = new Matrix();
flipMatrix.rotate(Math.PI);
flipMatrix.scale( -1, 1 );
flipMatrix.translate(0, picture.height);
reflection.draw(picture, flipMatrix);
for (var i:int = 0; i < picture.height; i++)
{
var rowFactor:Number = Math.max(0, 1 - (i / picture.height));
for (var j:int = 0; j < picture.width; j++)
{
var pixelColor:uint = reflection.getPixel32(j,i);
var pixelAlpha:uint = pixelColor>>24&0xff;
var pixelRGB:uint = pixelColor&0xffffff;
var resultAlpha:uint = pixelAlpha*rowFactor;
reflection.setPixel32(j, i, resultAlpha << 24 | pixelRGB);
}
}
reflection.applyFilter(reflection, reflection.rect, new Point(0, 0), new BlurFilter(4, 4, 3));
reflectionHolder=new Bitmap(reflection);
reflectionHolder.y=img.y+img.height;
reflectionHolder.x=img.x;
reflectionHolder.width = img.width;
reflectionHolder.height = img.height;
var uIComponent:UIComponent = new UIComponent();
uIComponent.addChild(reflectionHolder);
this.addElement(uIComponent);
}
protected function btn_clickHandler(event:MouseEvent):void
{
createReflection();
}
]]>
</fx:Script>
<s:Group height="100%" width="100%">
<s:BorderContainer backgroundColor="0x0d0d0d" height="100%" width="100%"/>
<s:Image id="img" height="100" width="200" />
<s:Button id="btn" click="btn_clickHandler(event)" />
</s:Group>
</s:WindowedApplication>
it shows result but the out put was not perfect...
Objective:- Reflected object should be same as the real Object and Have Some Distance From Real Object.

It will be very much code to show in one answer. Actually, I searched my very old archives, and I found my old class for reflection (2009 year). It will create reflection for you, It supports animated objects, and also distance from object to start of reflection. With only 2 lines of code:
var test:Sprite = new Sprite();
test.graphics.beginFill(0x990099);
test.graphics.drawRect(0, 0, 100, 50);
addChild(test);
test.x = test.y = 50;
//Reflection
//test - object that will be reflected
//40 - alpha, 40%
//200 - ratio, max value 0xFF or 255, with 0xFF you will see full object in reflection
//-1 - update frame rate, for animated objects
//0 - some dropoff... actually I don't remember it, don't use it by passing zero, It affects reflection bounds
//10 - distance to the reflection in pixels...
var vars:ReflectVars = new ReflectVars(test, 40, 200, -1, 0, 10);
var reflect:Reflect = new Reflect(vars);
And a result:
if you are interested in the class, I could move it to GitHub.

flipMatrix.translate(0, picture.height);
try changing this to
flipMatrix.translate(0, picture.height + 20);
OR
reflectionHolder.y=img.y+img.height;
try changing this to
reflectionHolder.y=img.y+img.height + 20;
for adding space between reflection & real picture

Related

actionscript3 to do something if null text field is found

In actionscript i have multiple dynamic text fields who are loading values from a php page using print.
...
vartxt1.text = receiveVars.phpVar1;
vartxt2.text = receiveVars.phpVar2;
vartxt3.text = receiveVars.phpVar3;
vartxt4.text = receiveVars.phpVar4;
vartxt5.text = receiveVars.phpVar5;
...
which is going very well.
Question: What i'm trying to do is, if let's say the vartxt2 is empty or has a specific value, the text field to be deleted, and the following text fields to be moved up in the place of the one deleted. The text field are one under other.
Thank you very much
Here the code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.TextInput;
private var txtArr:Dictionary = new Dictionary();
private var size:int;
public function init():void{
var arr:Array = ["aaaaaaa","bbbbbbbb","ccccccc","ddddddddddd","0","ffffffff","eeeeeee","0","ggggg","hhhhhh"];
var i:int = 0;
for each(var obj:String in arr){
var txt:TextInput = new TextInput();
txt.text = obj;
txt.id = "txt" + i.toString();
txtArr[i] = txt;
addChild(txt);
i++;
}
size = i;
}
public function sort():void{
for(var i:int; i < size - 1; i++){
var str:String = TextInput(txtArr[i]).text;
if(str==null || str.length==0 || str=="0"){
TextInput(txtArr[i]).text = TextInput(txtArr[i + 1]).text;
removeChild(txtArr[i]);
}
}
}
]]>
</mx:Script>
<mx:Button id="btn" label="Click Me" click="sort()"/>
</mx:Application>
I hope will be useful. You can dowload the Flex Project here.

Cannot correctly resize an image via action script

Hi I am trying to add an image when I click on a thumbnail.
I know I have to use a listener (Event.COMPLETE ?), but the image is not resizing correctly when I rotate the tablet.
I believe the problem is that I cannot resize the image within the addImage1() function, as the image has not yet loaded, but I cannot use newImg.width within the listener function to reset the image width.
Any help would be most appreciated.
Code follows:-)
<?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" title="ZOOM Pictues with Tap"
resize="view1_resizeHandler(event)">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import mx.events.ResizeEvent;
public var hasImageBeenAdded:Boolean = false;
private var imageLastWidth:Number;
private var imageLastHeight:Number;
private var zoomFactor:Number;
private var imageNumber:Number;
private var rhsKeepWidth:int;
private var rhsKeepHeight:int;
private var rhsKeep:Boolean = false;
protected function view1_resizeHandler(event:ResizeEvent):void
{
if(rhsKeepWidth > rhsKeepHeight) // Was Landscape is now Portrait
{
var tmpWidth2:int = rhsKeepWidth;
var tmpHeight2:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight2-lhs.width;
rhsKeepHeight = tmpWidth2+lhs.width;
}
else //Was Portrait is now Landscape
{
var tmpWidth1:int = rhsKeepWidth;
var tmpHeight1:int = rhsKeepHeight;
rhsKeepWidth = tmpHeight1-lhs.width;
rhsKeepHeight = tmpWidth1+lhs.width;
}
addImage1();
}
protected function removeAllImages():void
{
var totalElements : int = rhs.numElements;
for(var i:int=totalElements-1;i>=0;i--)
{
rhs.removeElementAt(i);
}
}
private function onImageLoaded(e:Event):void
{
var zoomFactor1:Number;
var zoomFactor2:Number;
imageLastWidth = e.target.sourceWidth;
imageLastHeight = e.target.sourceHeight;
if(rhsKeep != true) //Need to set the rhs VGroup dimensions
{
rhs.width = hGroup1.width-lhs.width;
rhs.height = hGroup1.height;
rhsKeep = true;
rhsKeepWidth = rhs.width;
rhsKeepHeight = rhs.height;
}
zoomFactor1 = rhsKeepWidth/imageLastWidth;
zoomFactor2 = rhsKeepHeight/imageLastHeight;
if(zoomFactor1 < zoomFactor2)
{
zoomFactor = zoomFactor1;
}
else
{
zoomFactor = zoomFactor2;
}
trace("zoomFactor=" + zoomFactor);
}
public function addImage1():void
{
var i:int;
var newImg:Image = new Image();
removeAllImages();
newImg.source = "images/1.jpg";
newImg.x = 0;
newImg.y = 0;
newImg.addEventListener(Event.COMPLETE,onImageLoaded);
rhs.addElementAt(newImg,0);
hasImageBeenAdded = true;
imageNumber = 1;
trace("Image Width= " + newImg.width);
newImg.scaleX = newImg.scaleY = zoomFactor;
}
]]>
</fx:Script>
<s:HGroup id="hGroup1" width="100%" height="100%">
<s:Scroller id="scrollerL" height="100%">
<s:VGroup id="lhs" width="15%" height="100%" gap="10"
horizontalAlign="center" verticalAlign="top">
<s:Image width="100" height="100" source="thumbs/1.jpg" click="addImage1()"/>
</s:VGroup>
</s:Scroller>
<s:Scroller id="scroller1" height="100%" width="100%">
<s:VGroup id="rhs" height="100%">
</s:VGroup>
</s:Scroller>
</s:HGroup>
</s:View>
Regarding the device orientation, you should use:
trace(Stage.deviceOrientation);
trace(Stage.orientation);
They are read-only strings outputting information regarding the device's and the screen's orientation. You may manually set the stage's orientation:
Stage.setOrientation(StageOrientation.DEFAULT);
Regarding the image loading, you need an eventListener for Event.COMPLETE and you should also cast the content as Image:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void {
trace("Image loaded");
// Handle code here
// Use: (loader.content as Image)
});
loader.load(new URLRequest("images/1.jpg"));

Flex/AS3: a generic click-and-drag zoom example, working except for one issue

I adopted the code from this website,
http://blog.ninjacaptain.com/2010/03/flex-chart-zoom-window/
Note that the bug mentioned in the web blog concerning displaying datatips appears to have been fixed (at least as of 4.5.1 SDK). I'm able to see the datatips fine.
The code works well except for one issue. I've added the complete code below so you can just copy and paste as a new Flex application and run it.
The problem is simply when the user clicks once without dragging, which gives the following error (make sure you click it AS SOON AS the app first runs):
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at mx.charts.chartClasses::CartesianDataCanvas/localToData()[E:\dev\4.5.1\frameworks\projects\charts\src\mx\charts\chartClasses\CartesianDataCanvas.as:580]
Is there a way to capture when the user clicks without dragging like this and call some function to handle it? Or, any way to avoid this error? Thanks for any comments/suggestions.
The code is:
<?xml version="1.0" encoding="utf-8"?>
<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"
initialize="init()" width="600" height="520">
<fx:Script>
<![CDATA[
[Bindable]
private var profits:Array;
private var dragStart:Point;
private var dragEnd:Point;
private var zooming:Boolean;
// initializes the data provider with random data
private function init():void{
profits = new Array({month: 0, profit: 15});
for(var i:int=1; i<40; i++)
profits.push({month: i, profit: Math.round(Math.random()*25-10)+profits[i-1].profit});
}
// sets the start point of the zoom window
private function startDraw(e:MouseEvent):void{
zooming = true;
dragStart = new Point(series1.mouseX, series1.mouseY);
}
// draws the zoom window as your mouse moves
private function showDraw(e:MouseEvent):void{
if(zooming){
dragEnd = new Point(series1.mouseX, series1.mouseY);
// finds the top-left and bottom-right ponits of the zoom window
var TL:Point = new Point(); // top-left point
var BR:Point = new Point(); // bottom-right point
if(dragStart.x < dragEnd.x){
TL.x = dragStart.x;
BR.x = dragEnd.x;
}
else{
TL.x = dragEnd.x;
BR.x = dragStart.x;
}
if(dragStart.y < dragEnd.y){
TL.y = dragStart.y;
BR.y = dragEnd.y;
}
else{
TL.y = dragEnd.y;
BR.y = dragStart.y;
}
// prevents the zoom window from going off the canvas
if(TL.x < 0) TL.x = 0;
if(BR.x > chartCanvas.width-1) BR.x = chartCanvas.width-1;
if(TL.y < 0) TL.y = 0;
if(BR.y > chartCanvas.height-1) BR.y = chartCanvas.height-1;
// draw the actual zoom window
chartCanvas.graphics.clear();
chartCanvas.graphics.lineStyle(1, 0x000000, 0.25);
chartCanvas.graphics.beginFill(0xd4e3f0,0.5);
chartCanvas.graphics.drawRect(TL.x, TL.y, BR.x-TL.x, BR.y-TL.y);
chartCanvas.graphics.endFill();
}
}
// clears the drawing canvas and sets the new max/mins
private function finishDraw(e:MouseEvent):void{
zooming = false;
chartCanvas.graphics.clear();
// converts the drag coordinates into axis data points
var chartValStart:Array = chartCanvas.localToData(dragStart);
var chartValEnd:Array = chartCanvas.localToData(dragEnd);
// sets the new maximum and minimum for both axes
haxis.minimum = (chartValStart[0] < chartValEnd[0]) ? chartValStart[0] : chartValEnd[0];
haxis.maximum = (chartValStart[0] < chartValEnd[0]) ? chartValEnd[0] : chartValStart[0];
vaxis.minimum = (chartValStart[1] < chartValEnd[1]) ? chartValStart[1] : chartValEnd[1];
vaxis.maximum = (chartValStart[1] < chartValEnd[1]) ? chartValEnd[1] : chartValStart[1];
}
// resets the axis max/mins
private function resetZoom():void{
haxis.minimum = NaN;
haxis.maximum = NaN;
vaxis.minimum = NaN;
vaxis.maximum = NaN;
}
]]>
</fx:Script>
<s:VGroup>
<mx:Panel title="Line Chart">
<mx:LineChart id="chart1"
mouseDown="startDraw(event)"
mouseMove="showDraw(event)"
mouseUp="finishDraw(event)"
width="510">
<!-- zoom window is drawn here -->
<mx:annotationElements>
<mx:CartesianDataCanvas id="chartCanvas"/>
</mx:annotationElements>
<mx:horizontalAxis>
<mx:LinearAxis id="haxis"/>
</mx:horizontalAxis>
<mx:verticalAxis>
<mx:LinearAxis id="vaxis"/>
</mx:verticalAxis>
<mx:series>
<mx:LineSeries filterData="false" id="series1" xField="month" yField="profit"
displayName="Profit" dataProvider="{profits}"/>
</mx:series>
</mx:LineChart>
</mx:Panel>
<mx:Button label="Reset Zoom" click="resetZoom()" />
</s:VGroup>
</s:Application>
UPDATE:
Here's the solution, in case it's useful to others. I've added an if statement to check for null dragStart and dragEnd values, as discussed in the answer below. Also, I've removed the drop shadow that flex places by default on the line series, so a warning doesn't appear if the zoom area the user selects is too small.
<?xml version="1.0" encoding="utf-8"?>
<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"
initialize="init()" width="600" height="520">
<fx:Script>
<![CDATA[
[Bindable]
private var profits:Array;
private var dragStart:Point;
private var dragEnd:Point;
private var zooming:Boolean;
// initializes the data provider with random data
private function init():void{
profits = new Array({month: 0, profit: 15});
for(var i:int=1; i<40; i++)
profits.push({month: i, profit: Math.round(Math.random()*25-10)+profits[i-1].profit});
}
// sets the start point of the zoom window
private function startDraw(e:MouseEvent):void{
zooming = true;
dragStart = new Point(series1.mouseX, series1.mouseY);
}
// draws the zoom window as your mouse moves
private function showDraw(e:MouseEvent):void{
if(zooming){
dragEnd = new Point(series1.mouseX, series1.mouseY);
// finds the top-left and bottom-right ponits of the zoom window
var TL:Point = new Point(); // top-left point
var BR:Point = new Point(); // bottom-right point
if(dragStart.x < dragEnd.x){
TL.x = dragStart.x;
BR.x = dragEnd.x;
}
else{
TL.x = dragEnd.x;
BR.x = dragStart.x;
}
if(dragStart.y < dragEnd.y){
TL.y = dragStart.y;
BR.y = dragEnd.y;
}
else{
TL.y = dragEnd.y;
BR.y = dragStart.y;
}
// prevents the zoom window from going off the canvas
if(TL.x < 0) TL.x = 0;
if(BR.x > chartCanvas.width-1) BR.x = chartCanvas.width-1;
if(TL.y < 0) TL.y = 0;
if(BR.y > chartCanvas.height-1) BR.y = chartCanvas.height-1;
// draw the actual zoom window
chartCanvas.graphics.clear();
chartCanvas.graphics.lineStyle(1, 0x000000, 0.25);
chartCanvas.graphics.beginFill(0xd4e3f0,0.5);
chartCanvas.graphics.drawRect(TL.x, TL.y, BR.x-TL.x, BR.y-TL.y);
chartCanvas.graphics.endFill();
}
}
// clears the drawing canvas and sets the new max/mins
private function finishDraw(e:MouseEvent):void{
zooming = false;
chartCanvas.graphics.clear();
if (dragStart && dragEnd) { // Solution to original posted quesion
// converts the drag coordinates into axis data points
var chartValStart:Array = chartCanvas.localToData(dragStart);
var chartValEnd:Array = chartCanvas.localToData(dragEnd);
// sets the new maximum and minimum for both axes
haxis.minimum = (chartValStart[0] < chartValEnd[0]) ? chartValStart[0] : chartValEnd[0];
haxis.maximum = (chartValStart[0] < chartValEnd[0]) ? chartValEnd[0] : chartValStart[0];
vaxis.minimum = (chartValStart[1] < chartValEnd[1]) ? chartValStart[1] : chartValEnd[1];
vaxis.maximum = (chartValStart[1] < chartValEnd[1]) ? chartValEnd[1] : chartValStart[1];
}
// reset values for next time
dragStart=null;
dragEnd=null;
}
// resets the axis max/mins
private function resetZoom():void{
haxis.minimum = NaN;
haxis.maximum = NaN;
vaxis.minimum = NaN;
vaxis.maximum = NaN;
}
]]>
</fx:Script>
<s:VGroup>
<mx:Panel title="Line Chart">
<mx:LineChart id="chart1"
mouseDown="startDraw(event)"
mouseMove="showDraw(event)"
mouseUp="finishDraw(event)"
width="510">
<!-- zoom window is drawn here -->
<mx:annotationElements>
<mx:CartesianDataCanvas id="chartCanvas"/>
</mx:annotationElements>
<mx:horizontalAxis>
<mx:LinearAxis id="haxis"/>
</mx:horizontalAxis>
<mx:verticalAxis>
<mx:LinearAxis id="vaxis"/>
</mx:verticalAxis>
<mx:series>
<mx:LineSeries filterData="false" id="series1" xField="month" yField="profit"
displayName="Profit" dataProvider="{profits}"/>
</mx:series>
<mx:seriesFilters>
<fx:Array/>
</mx:seriesFilters>
</mx:LineChart>
</mx:Panel>
<mx:Button label="Reset Zoom" click="resetZoom()" />
</s:VGroup>
</s:Application>
You are getting this error because the variable dragEnd is never set if the user just clicks the mouse. The easiest way to prevent this would be check for null values inside your finishDraw function:
private function finishDraw(e:MouseEvent):void
{
zooming = false;
chartCanvas.clear();
if(dragStart && dragEnd)
{
//your stuff here
//...
}
//reset values for next time
dragStart=null;
dragEnd=null;
}
And this should avoid any further 1009 Errors there. Beware I am getting some Warnings if I drag a tiny small zoom window and then release the mouse because Flash has a limit on how big a DisplayObject can be, so you should validate also the dimensions of the zoom window.
Hope this helps!

EFFECT_REPEAT not firing on every iteration of Animate instance when losing focus

I'm not sure if that title is descriptive enough, but here is the basic issue. I have a spark.effects.Animate instance repeating n times with a listener on the EFFECT_REPEAT event. In that event's listener, I'm incrementing a variable. Logic would dictate that if the variable started at 0 and the animation was played with a repeatCount of 3, the variable would be 2 when finished. This works fine, until I focus a different tab. When doing this, on occasion, the repeat event isn't fired/handled (or the animation is just not actually doing the animation) and my count isn't correct when finished.
This is a fully functioning example built against Flex 4.5. To duplicate just click the GO button and maintain focus on the TAB. Then click it again and switch tabs and switch back. The counts don't match.
How can I fix this so that the repeat event is called consistently?
<?xml version="1.0" encoding="utf-8"?>
<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" width="600" height="400" applicationComplete="application1_applicationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.controls.Image;
import mx.events.EffectEvent;
import mx.events.FlexEvent;
import spark.effects.Animate;
import spark.effects.animation.MotionPath;
import spark.effects.animation.SimpleMotionPath;
private var animate:Animate;
private var someCounter:int = 0;
protected function application1_applicationCompleteHandler(event:FlexEvent):void
{
// Create the graphic
var img:Image = new Image();
img.source = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
// Add the graphic
addElement( img );
// Create the motion path
var smp:SimpleMotionPath = new SimpleMotionPath();
smp.property = "x";
smp.valueFrom = 0;
smp.valueTo = this.width - 275;
// Add the motion path to a Vector
var paths:Vector.<MotionPath> = new Vector.<MotionPath>();
paths.push( smp );
// Create the animation
animate = new Animate();
animate.easer = null;
animate.target = img;
animate.duration = 150;
animate.repeatCount = 15;
animate.motionPaths = paths;
animate.addEventListener( EffectEvent.EFFECT_REPEAT, animate_effectRepeatHandler );
animate.addEventListener( EffectEvent.EFFECT_END, animate_effectEndHandler );
}
private function animate_effectRepeatHandler( event:EffectEvent ):void
{
lblCounter.text = someCounter.toString();
someCounter++;
}
private function animate_effectEndHandler( event:EffectEvent ):void
{
lblCounter.text = someCounter.toString(); // Sometimes doesn't equal animate.repeatCount - 1
}
protected function button1_clickHandler(event:MouseEvent):void
{
if( !animate.isPlaying )
{
someCounter = 0;
animate.play();
}
}
]]>
</fx:Script>
<mx:Label id="lblCounter" horizontalCenter="0" bottom="50" width="150" height="50" textAlign="center" />
<mx:Button horizontalCenter="0" bottom="0" label="GO" width="150" height="50" click="button1_clickHandler(event)" />
</s:Application>

Adobe Flex creating polygon

How to create a polygon in Adobe flex 3.0
You draw a bunch of lines connecting the points of the polygon.
As a quick example:
function drawPolygon(first, ... rest) {
graphics.moveTo(first.x, first.y);
for(var i = 0; i < rest.length; i++) {
graphics.lineTo(rest[i].x, rest[i].y);
}
graphics.lineTo(first.x, first.y);
}
May be some minor syntax errors, but you get the idea. You'd call it by passing a bunch of Point objects indicating the points of the polygon.
Try this sample
<?xml version="1.0" encoding="utf-8"?>
<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"
xmlns:esri="http://www.esri.com/2008/ags">
<fx:Script>
<![CDATA[
import com.esri.ags.Graphic;
import com.esri.ags.SpatialReference;
import com.esri.ags.Units;
import com.esri.ags.geometry.Geometry;
import com.esri.ags.geometry.MapPoint;
import com.esri.ags.geometry.Polygon;
import com.esri.ags.geometry.Polyline;
import com.esri.ags.utils.GeometryUtil;
import mx.utils.StringUtil;
private const sr:SpatialReference = new SpatialReference(4326);
protected function onCreatePolyline(event:MouseEvent):void
{
addMessage("Create polyline clicked");
var pts:Array = new Array();
for (var i:int; i < 10; i++) // add 10 random points to path
{
var pt:MapPoint = new MapPoint(Math.random()*10000, Math.random()*10000, sr);
pts.push(pt);
}
var pl:Polyline = new Polyline(new Array(pts), sr);
var lengths:Array = GeometryUtil.geodesicLengths(new Array(pl), Units.KILOMETERS);
if (lengths != null && lengths.length > 0)
{
addMessage(StringUtil.substitute("polyline created with length {0} km", lengths[0]));
}
addGraphic(pl);
}
protected function onCreatePolygon(event:MouseEvent):void
{
addMessage("Create polygon clicked");
var pts:Array = new Array();
for (var i:int; i < 10; i++) // add 10 random points to ring
{
var pt:MapPoint = new MapPoint(Math.random()*10000, Math.random()*10000, sr);
pts.push(pt);
}
var pg:Polygon = new Polygon(new Array(pts), sr);
var areas:Array = GeometryUtil.geodesicAreas(new Array(pg), Units.SQUARE_KILOMETERS);
if (areas != null && areas.length > 0)
{
addMessage(StringUtil.substitute("polygon created with area {0} kmĀ²", Math.abs(areas[0])));
}
addGraphic(pg);
}
private function addMessage(message:String):void
{
log.text = StringUtil.substitute("> > > {0}\n{1}", message, log.text);
}
private function addGraphic(geometry:Geometry):void
{
var gr:Graphic = new Graphic(geometry);
grLayer.clear();
var grId:String = grLayer.add(gr);
addMessage(StringUtil.substitute("graphic added with id='{0}'", grId));
map.initialExtent = geometry.extent;
map.zoomToInitialExtent();
}
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout gap="10"
paddingBottom="10"
paddingLeft="10"
paddingRight="10"
paddingTop="10"/>
</s:layout>
<s:Button label="Create polyline"
click="onCreatePolyline(event)"/>
<s:Button label="Create polygon"
click="onCreatePolygon(event)"/>
<s:TextArea id="log"
width="100%"
height="100%"/>
<esri:Map id="map"
zoomSliderVisible="false"
minHeight="200"
width="100%">
<esri:GraphicsLayer id="grLayer" />
</esri:Map>
</s:Application>