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!!


18
May 10

Diagonol barChart

Its not the most practical component though but for a slick “Reports UI” I had to develop a diagonal bar chart component that can be used to display a barchart 45degrees to the horizontal axis. At first i thought of solving this by using a conventional Flex Barchart but it turned out to be too much of effort in styling the barchart to look like the Screenshot, So i went ahead and wrote diagonal barChart from scratch.

Limitations :
1) Chart not re-sizable
2) Chart written with embedded font (otherwise label cant be rotated).
3) Chart cannot be configured with direction, barThickness and barGap.

Features:
1) “n” Diagonal bars can be drawn on screen : i have tested it with 1000 but 50 bars are more practical.
2) top 10 bars drawn + Others : this feature enables you to see top 10 bars with the rest of the bars clubbed into others
3)sorted/unsorted bars by value.

well do try it out and if you like the widget do let me kno.

Source here

Demo here


18
May 10

Random color generator

I am sure there were many times in the past that you would have wanted to have a function that could return you random colors. Well at least i have faced this problem many times, Mostly when i am giving a demo for a new component which deals with various color ranges.

Following is the code to generate Random colors:

1
2
3
4
5
6
7
8
9
private var redBias:Number = 0xFF;
private var greenBias:Number = 0xFF;
private var blueBias:Number = 0xFF;

private function getRandomColor():uint{
var ct:ColorTransform = new ColorTransform(1,1,1,1,Math.random()*redBias, Math.random()*greenBias, Math.random()*blueBias);
var color:uint = ct.color;
return color;
}

you can also modify the above code to return you a range in a specific color range this can be done by making any 2 colors constant instead of using a random number. Well then enjoy the code and do post in any new cool things that you can do with this piece of code.

for more know-how read the following post : ColorTransform


10
May 10

Inspectable : metatag that makes your code fool proof

If you are building a custom components which will be used by other developers <mxml> style  wont it be cool for them to see the  bindable properties in a popup selectable values (i.e. true/false) via code completion in Flex Builder. Plus it could  also to show in the Properties Panel in design view and the teammate has the ability to choose a property value.

in short making your component FOOOL proof  ;). Well then “Inspectable” is your best friend.

Usage:

1
2
[Inspectable( defaultValue=false,verbose=1, category="Other", enumeration="true,false")]
[Bindable] public var aintThisCool : Boolean;

If your like what you have read and want to learn more follow the link:Flex Metatags


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 →


3
Mar 10

Always Call Super in Item Renderer’s Override Methods

Today I came across a bug where I was using an item renderer in a data grid and the row didn’t highlight when you mouse over it and wouldn’t get selected when you clicked on it (ie, moused over or clicked on the column, not the entire row). The item renderer consisted of 2 Label component.

At first, it was tough to see what the problem could have been. The item renderer is very simple, I have used more complicated item renderers elsewhere that don’t have this problem.

That’s when I noticed that my data setter override didn’t look quite right:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
        override public function set data(value:Object):void{

            _data = value;
            if(value){
                if(parseInt(value["growth"])>0)
                    this.setStyle("color",LOW_STATE);
                else if(parseInt(value["growth"])== 0)
                    this.setStyle("color",NORMAL_STATE);
                if(parseInt(value["growth"])&lt;0)
                    this.setStyle("color",HIGH_STATE);
                   
                this.text = value["growth"]+"%";
                }
       }

I was this close to trying to hack in something using the mouseover and mouseclick handlers, when I realized I just needed to do this little change : “super.data = value”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        override public function set data(value:Object):void{
            // the missing line that made all the difference
                super.data = value;

            _data = value;
            if(value){
                if(parseInt(value["growth"])>0)
                    this.setStyle("color",LOW_STATE);
                else if(parseInt(value["growth"])== 0)
                    this.setStyle("color",NORMAL_STATE);
                if(parseInt(value["growth"])&lt;0)
                    this.setStyle("color",HIGH_STATE);
                   
                this.text = value["growth"]+"%";
                }
       }

Apparently something in the super class’s data setter does something vitally important, and you really shouldn’t skip that. If you do, BAD stuff will happen.


2
Mar 10

useHandCursor = Pain in the arse!

I was creating a UIcomponent called the “FilterIndicator” which looks like a button but has a button inside itself to remove the button all-together from the stage. FilterIndicator by default will have a toggle behavior differenciated by the background color: if the filter is active the bgColor is green but if the filter is applied it becomes red. the whole component extends Canvas.

The task was to show a hand cursor whenever the user moves his mouse over this component. So far it had turned out to be a pain in the ass till i found the solution.

Well the problem with useHandcursor started when i tried to show cursor on the canvas. firstly this was not working when i did try this out with various combination i found out that MouseChildren = “false” property actually controls the behavior of useHandcursor.

solution :
useHandCursor=”true” buttonMode=”true” mouseChildren=”false”

IMPORTANT: mouseChildren=”false” might cause the mouseclick of the subsequent below components to not fire at all.


Pages: 1 2 3 4 5 6 Next