Posts Tagged: flex


13
May 11

Export to Jpeg in flex.

There is always a need to way to export some sort of a report out to the user, previously I used the classical use of a serverside script in Java or PHP to enable user to take a screenshot of the component or the entire application. Since the flash player 10 provides the feature to save local file using file reference I am going to exploit that feature and export some BITMAP content into a Jpeg file.

following is the code for taking a snapshot of the component on some event/action

Prerequisite for making this components work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//file reference declaration to enable user to save file to local system.
private var file:FileReference = new FileReference();

//function can be called on button click or context menu click or any other interaction
private function captureIt():void{
var df : DateFormatter = new DateFormatter();
df.formatString = "DD-MM-YY HH:NN"
var bitmapData:BitmapData = new BitmapData(this.width, this.height);
bitmapData.draw(this,new Matrix());
var bitmap : Bitmap = new Bitmap(bitmapData);
var jpg:JPEGEncoder = new JPEGEncoder();
var ba:ByteArray = jpg.encode(bitmapData);
var dt : Date = new Date();
var dtStr : String = df.format(dt.time);
file.save(ba,'Screenshot at'+dt.time+'.jpg');
}

Explanation

BitmapData ()
The BitmapData () function takes a height and width of the component which has to be converted to image, i have used this you can very well use any UIComponent or DisplayObject.

bitmapData.draw(this,new Matrix ());
This is the place where the actual conversion takes place (where the bitmap data is drawn), Again you can use any UIComponent or DisplayObject in this place.

Bitmap Encoding: jpg.encode (bitmapData);
The component or screen area to be captured is converted into BITMAP data so that it could be encoded into Jpeg file format for saving it, you can also use a PNG or GIF encoder in this place as per your requirement. At this place the Bitmap data is encoded into a JPEG file format.

var ba : ByteArray = jpg.encode (bitmapData);
Since BITMAP data cannot be saved directly to the local system we first convert it into a ByteArray.

Date : dt.time
The date is only used to give each screenshot a unique timestamps so that each time the function is called a new file is saved.

file.save ( ba,’Screenshot at’+dt.time+’.jpg’ );
Now we pass the byte array to the file reference and also pass the name by which the file has to be saved, as shown in the function above.

Vollia you can now save JPEG file to your local file system via Flex without using any third party Serverside script to do so. No more HTTP request and error handling to take care of.

GO MAKE THE WORLD A BETTER PLACE
Say no to paper, No need to print graphs when you can save them to jpeg


12
May 11

Power of Flash Catalyst

Here is Kevin Lynch’s Keynote from the Web 2.0 conference where he shows how to build a full application using Illustrator, Flash Catalyst, Flex Builder, Flex and the Facebook ActionScript 3 API.


5
May 11

Save file as PDF in flex

Saving content as PDF from flex had always been a hassle, We know that doing such file operations in AIR is much simpler but due to the file saving ability added in Flash player 10 One can easily save files to the local system.

The next big question is how do i convert my content to PDF format so that it can be correctly saved into the file. Well for that folks at AlivePDF have done a gr8 job and now any one can encode their content into pdf and offer for download. They have a good documentation section which you can read and create more complex stuff.

For beginners i am writing a small example in which i will let the user download a PDF with embedded text or the Image depending on his choice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<mx:application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="522">
<mx:script>
    < ![CDATA[
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.text.*;
    import flash.utils.ByteArray;

    import mx.graphics.codec.JPEGEncoder;

    import org.alivepdf.layout.Orientation;
    import org.alivepdf.layout.Size;
    import org.alivepdf.layout.Unit;
    import org.alivepdf.pdf.PDF;
    import org.alivepdf.saving.Method;

    protected var fileRefPDF:PDF;

    private function onSaveClicked(e:Event):void
    {
    fileRefPDF = new PDF(Orientation.PORTRAIT, Unit.MM, Size.LETTER);
    fileRefPDF.addPage();

    if(check.selected){
    fileRefPDF.addImage(pics);
    fileRefPDF.addMultiCell(200,5,myname.text);
    }else{
    fileRefPDF.addMultiCell(200,5,myname.text);
    }

    var bytes:ByteArray = fileRefPDF.save(Method.LOCAL);
    var file:FileReference = new FileReference();
    file.save(bytes,"Untitled.pdf");
    }



    ]]>
</mx:script>

    <mx:canvas id="pics">
        <mx:image source="@Embed('hello.jpg')" x="198" y="19" width="311" height="208"/>
        <mx:label text="Oh!! Hi," x="330" y="166"/>
        <mx:label text="{myname.text}" x="330" y="184"/>
    </mx:canvas>



    <mx:label top="33" left="14" text="Save as PDF Test "  fontWeight="bold" fontSize="15"/>    
    <mx:button click="onSaveClicked(event)" label="Save to PDF" id="saveBtn" x="14" y="148"/>
    <mx:label text="Enter your name:" y="72" x="14"/>
    <mx:textinput id="myname"  x="14" y="90"/>
    <mx:checkbox id="check" label="Save image" selected="false"  x="14" y="121"/>
</mx:application>

the Screenshot of the same can be seen below.

Note: please include the AlivePDF swc in your project.

I have just skimmed the surface of the ocean with the above code. but you can write your own brew of concoction that could possibly bring WORLD PEACE :)

(-_-) happy loafing !


11
Apr 11

Flash “like” charts for iPad and iPhone

We already know the huge gap thats been created by Apple not adopting “Flash” to run on there device. The end users and developer pay the toll as they have to adapt to this scenario and live with the limitation of either viewing their content in different visual component OR come up with a solution that works both for Flash enabled device and non Flash device like apple iPhone and iPad.

I am happy to announce that Folks at Amcharts are doing an awesome task for bridging the gap between flash users and non flash users by providing a charing component for both kinds of devices.

Now you can seamlessly view our data on both the device by using their FLASH/FLEX component or their JAVASCRIPT charting components.

How can this be done?
Use the HTML wrapper to decide if the device can handle flash or not. (can be done even with JS) Once you know what device you are running you can choose which kind of component to load. This gives you a seamless solution for your Business and YES it will support the normal flashbased platform as well as NON flash platforms

Important to note: you will have to follow the conventional MVC model to achieve. Keep VIEW and DATA separate.

 

Thanks for coming up with this solution. You guys at AmCharts ROCK!!


10
Mar 10

Flex component lifecycle and event flow explained

Learned something new from Ted today
Read original post by Ted here

Flex is an event driven programming model and everything happens due to an event. Looking at the MXML code can confuse most of the developers unless they haven’t looked at the internal class of flex components. If we were to compare Flex, HTML and FLASH in terms of component instantiation.

  • HTML instantiates top to bottom
  • Flash executes across frames starting at Frame zero.
  • Flex on the other had is a bit different.

When I started  learning Flex, I struggled with understanding event flow and instantiation in MXML. I was puzzled because I really didn’t understand how event chain started and what happened inside a component to make it finally render on screen. Initially I used to run into numerous runtime  null point exception since i used to think i could access a property of  an object  thinking it would have been created.

Anyhow the key is understanding the event basics and seeing the initialization and event flow, Lets look at a sample application that i have written to explain this. The structure of the application cann be understood by the following diagram.

With this Demo app there is no visual clue that you will get  as an output to understand the event flow and instantiation step. its the TRACE statements that are important to explain  how the event  flow and instantiation happens. Below is the code for the same.

Continue reading →


18
Feb 10

Is flex timer Accurate?

Would you would expect timers in ActionScript 3.0 to be accurate??

“yes, of course!” But there’s a problem:

If you set a Timer to go off indefinitely (i.e., with a repeatCount of 0), it appears that the timer doesn’t start the next interval until the listener function returns. So if you don’t correct for this, then your timer function will creep by the duration of the listener function. If your listener function does something that’s potentially lengthy, you might want to execute it with a callLater() so that the timer isn’t affected. But the timer will still creep unless you apply a correction. Here’s some sample code that demonstrates the effect, side-by-side with a correction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
< ?xml version="1.0" encoding="utf-8"?>
<mx :Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="{onCreationComplete(event)}">
    </mx><mx :Script>
        < ![CDATA[
            import mx.utils.StringUtil;
            import mx.events.FlexEvent;
            private const BASE_INTERVAL:Number = 1000;
            private var _creepingTimer:Timer = new Timer(BASE_INTERVAL);
            private var _steadyTimer:Timer = new Timer(BASE_INTERVAL);
            private var _startTime:Date;
 
            private function onCreationComplete(e:FlexEvent) : void
            {
                _creepingTimer.addEventListener(TimerEvent.TIMER, onCreepingTimer);
                _creepingTimer.start();
                _steadyTimer.addEventListener(TimerEvent.TIMER, onSteadyTimer);
                _steadyTimer.start();
                _startTime = new Date();
            }
 
            private function onCreepingTimer(e:TimerEvent) : void
            {
                var now:Date = new Date();
                var deltaMS:int = now.time - _startTime.time;
                uiCreepingLog.text += StringUtil.substitute("\r{0}", deltaMS);
            }
 
            private function onSteadyTimer(e:TimerEvent) : void
            {
                var now:Date = new Date();
                var deltaMS:int = now.time - _startTime.time;
                uiSteadyLog.text += StringUtil.substitute("\r{0}", deltaMS);
                var offset:int = deltaMS % BASE_INTERVAL;
                _steadyTimer.delay = offset < 500 ? BASE_INTERVAL - offset : BASE_INTERVAL;
            }
 
 
        ]]>
    </mx>
    <mx :HBox width="100%" height="100%">
        <mx :TextArea id="uiCreepingLog" width="50%" height="100%" text="Creeping timer:"/>
        <mx :TextArea id="uiSteadyLog" width="50%" height="100%" text="Steady timer:"/>
    </mx>

read the orignal post at : joy of flex


10
Jul 09

Dynamically add remove columns in a datagrid

I had a hard time figuring out how to add remove columns  dynamically from a datagrid and after lots of code iterations I have reached a workable scenario. Right now the code is fairly easy to understand and can be enhanced to a gr8 deal,

I still need to add other important functionalities.

  • Close headerrenderer for each column
  • delete entire row functionality
  • user defined default state
  • and much more…

Dint get the time to complete this post but someday i will surely post a complete working APP
by that time check out the code  USE AND MODIFY AS PLEASED!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
< ?xml version="1.0" encoding="utf-8"?>
<mx:application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="100%" height="100%" >
   
    <mx:hdividedbox height="100%" width="100%" dividerRelease="handleDivderRelease()">
    <mx:script>
        < ![CDATA[
            import mx.controls.CheckBox;
            import mx.controls.ComboBox;
            import mx.controls.dataGridClasses.DataGridColumn;
           
            public var counter : int = 0;
            public var conDataProvider : Array =[{label : "col1", data : "c1"},
                {label : "col2", data : "c2"},
                {label : "col3", data : "c3"},
                {label : "col4", data : "c4"},
                {label : "col5", data : "c5"},
                {label : "col6", data : "c6"}];
           
           
            private function hideShowColumns():void{
                var actualColumns:Array = ResultGrid.columns;
                var actualSelectedColumns:Array =  lstColumns.selectedItems;
                var dataGridColumn:DataGridColumn;
                var sDataField:String;
                var sDataFieldCur:String;
                var columnVisible:Boolean
                for (var i:int=0;i<actualColumns.length;i++)  {
                    columnVisible = false
                    dataGridColumn = actualColumns[i];
                    sDataField = dataGridColumn.dataField;
                    for (var j : int = 0; j < actualSelectedColumns.length; j++)  {
                        if(actualSelectedColumns[j] == null) continue;
                        sDataFieldCur = actualSelectedColumns[j].data;
                        if (sDataFieldCur == sDataField)  {
                            columnVisible = true;
                            break;
                        }
                    }      
                    if (columnVisible) {
                        dataGridColumn.visible = true;
                    }else  {
                        dataGridColumn.visible = false;
                    }
                }
            }
           
            private function selectAll():void{
                lstColumns.selectedIndices=[0,1,2,3,4,5];
                hideShowColumns();
            }
           
            private function clearAll():void{
                lstColumns.selectedIndices=[];
                hideShowColumns();
            }
           
            private function setDefault():void{
                lstColumns.selectedIndices=[0,1,2,3];
                hideShowColumns();
            }
           
            private function handleDivderRelease():void{
                if(counter == 0){
                    controlBox.width =0
                }else if(counter == 1){
                    controlBox.width =120
                }
                counter = (counter +1)%2;
            }
           
        ]]>
    </mx:script>
   
    <mx:vbox id="controlBox" height="100%" width="120" maxWidth="120"  verticalGap="0" horizontalScrollPolicy="off">
        <mx:label text="Selected columns" fontWeight="bold" />
        <mx:list height="100%" width="120" id="lstColumns" dataProvider="{conDataProvider}"
                 labelField="label" borderColor="#000000"
                 allowMultipleSelection="true" click="hideShowColumns()"
                 selectedIndices="[0,1,2,3]"/>
        <mx:textarea wordWrap="true" selectable="false" editable="false" borderStyle="none"
                     text="For multiple selection use ctrl/shift keys" width="120" />
        <mx:spacer height="5" />
        <mx:button label="Select All"  width="100%" click="selectAll()"/>
        <mx:button label="Default"  width="100%" click="setDefault()"/>
        <mx:button label="Clear All" width="100%" click="clearAll()"/>
    </mx:vbox>
    <mx:vbox height="100%" width="100%">
        <mx:datagrid height="100%" id="ResultGrid" selectedIndex="0" enabled="true" selectable="true" creationComplete="init()">
            <mx:columns>
                <mx:datagridcolumn headerText="col1" dataField="c1" visible="true" />
                <mx:datagridcolumn headerText="col2" dataField="c2" visible="true" />
                <mx:datagridcolumn headerText="col3" dataField="c3" visible="true" />
                <mx:datagridcolumn headerText="col4" dataField="c4" visible="true" />
                <mx:datagridcolumn headerText="col5" dataField="c5" visible="false" />
                <mx:datagridcolumn headerText="col6" dataField="c6" visible="false" />
            </mx:columns>
        </mx:datagrid>
    </mx:vbox>
</mx:hdividedbox>
</mx:application>


21
May 09

Flex regular expression cheatsheet

regular-expressions-cheat-sheet-v2

to see large version, right click save as image


21
May 09

Flex "Bindable" tag

the Bindable tag is widely used in flex and in simpleterms its used to bind an entity to other entity if there is a change in the source.
The tag can have the following form:

[Bindable]
public var foo;

The Flex compiler automatically generates an event named propertyChange for the property. If the property value remains the same on a write, Flex does not dispatch the event or update the property.

You can also specify the event name, as the following example shows:

[Bindable(event="fooChanged")]
public var foo;

In this case, you are responsible for generating and dispatching the event, typically as part of some other method of your class. You can specify a [Bindable] tag that includes the event specification if you want to name the event, even when you already specified the [Bindable] tag at the class level.

In order for binding to work you need to make sure changes to the data are known to the framework. Unlike most of dynamic languages implementations, ActionScript 3 is built for speed and heavily utilizes direct access to the properties and methods. In this situation the only way for data to notify the world about the changes is to embed the code to fire change events.

Flex compiler helps in a big way by introducing [Bindable] and [Managed] tags. If you prefix your variable with [Bindable] tag, compiler does the following:
1. Inspects every public property and setter of you variables class and generates wrapper getters/setters that adds event notification.
2. Every time “bindable” property is being used, compiler references these getters/setters instead of original properties


20
May 09

Remove “Flex Data Visualization Trial” using actionscript

I did a small hack in the Flex charting code and removed the Trial message from the Charting component by writing 1 simple actionscript lines.

what you need to do is in the creationcomplete of any charting component write the following code

1
2
3
4
5
6
7
8
9
private function removeTrialMsg():void{ 
          var arra : Array = new Array();
            for(var i:int =0;i&lt;this.numChildren;i++){
               arra.push(this.getChildAt(i));
            }

// the above 4 lines are just to check  what r the childs added
(this.getChildAt(this.numChildren-1) as TextField).htmlText = " ";
}

we  tried to set visible false but that dint work we also tried to remove the textfield child alltogether  but that too dint work but finally it was the html text property of the textfield that gave way.

now you can also add your custom  trial message to your application :)

just replace the blank with your text for example:

1
2
3
private function removeTrialMsg():void{ 
      (this.getChildAt(this.numChildren-1) as TextField).htmlText = "this is TRIAL";
}

But its better that you buy your own licence key for charting. The above example was basically for educational purpose. have fun :)

trial


Pages: 1 2 3 4 Next