Create a button with font-icon and pure actionscript 3

As I see that the font-icon technique is becoming very popular, and I personally like it very much I decided to post some code of how to create a simple button with an Icon using only AS3 as it is lighter and much faster on mobile devices.

We will create a class that will hold our button, as you will see I have embedded the signify font, (signify is a font which has icons corresponding to letters and numbers):

[cc lang=”Actionscript”]
package
{
import flash.display.GradientType;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Matrix;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.getQualifiedClassName;

public class UIButton extends Sprite
{
[Embed(source=”fonts/signify-webfont.ttf”, fontFamily=”Signify”, embedAsCFF=”false”)]
public static var signify:String;

private var myShape:Shape;
private var gradientBoxMatrix:Matrix;
private var masterWidth:Number;
private var masterHeight:Number;

private var radius:Number = 10;

public function UIButton()
{
super();
}
}
}
[/cc]

Next we will create the main function that draws the button:

[cc lang=”Actionscript”]
public function createButton(gradientColor_:Array = null, width:Number=120, height:Number=60, x:Number=10, y:Number=10, _text:String = ‘E’)
{

}
[/cc]

First we draw the matrix for the gradients and the rectangle:

[cc lang=”Actionscript”]
myShape = new Shape();
gradientBoxMatrix = new Matrix();
gradientBoxMatrix.createGradientBox(width, height, Math.PI/2, 0, 0);
myShape.graphics.beginGradientFill(GradientType.LINEAR, gradientColor_, [1,1,1], [0,128,255],gradientBoxMatrix);
myShape.graphics.lineStyle(2, 0x1e1e1e);
myShape.graphics.drawRoundRect(0,0,width,height,radius);
myShape.graphics.endFill();
[/cc]

And now we create the icon:

[cc lang=”Actionscript”]
var tfl:TextField = new TextField();
tfl.text = _text;
tfl.width = width/2;
tfl.height = height/2;
tfl.textColor = 0x0e0e0e;
tfl.embedFonts = true;
var tf:TextFormat = new TextFormat(‘Signify’,38,0x0e0e0e); //here we define the embedded font
tfl.setTextFormat(tf);
tfl.selectable = false;

tfl.x = width/2 – tfl.textWidth+19;
tfl.y = -10;
[/cc]

finally we add them to the display object:

[cc lang=”Actionscript”]
this.addChild(myShape);
this.addChild(tfl);
[/cc]

we can easily call this class by doing:

[cc lang=”Actionscript”]
var button:UIButton = new UIButton();
button.createButton([0xffffff,0xf1f1f1,0xf8f8f8]);
addChild(button);
[/cc]

View an example here: MobileUI

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex 4, Grid Gallery effect

Here’s an after midnight project I undertook.

So I’ve always wanted that grid gallery layout and effect for my images or slides. So I decided to make it happen. A useful tool in this was TweenMax from the greensock library (I love their tween effects, easy and to the point).

So here’s the simple code for this grid effect:

<?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” minWidth=”955″ width=”600″ height=”400″ backgroundColor=”#171717″ minHeight=”600″>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import com.greensock.*;
import com.greensock.easing.*;
//var imgArr = new Array(“assets/img1.jpg”,”assets/img2.jpg”,”assets/img3.jpg”,”assets/img4.jpg”);

private function moveGrid(slideNum)
{
switch(slideNum)
{
case 1:
TweenMax.to(grid, 1, {x:0,y:0, ease:Quint.easeOut});

break;
case 2:
TweenMax.to(grid, 1, {x:-400,y:0, ease:Quint.easeOut});
break;
case 3:
TweenMax.to(grid, 1, {x:0,y:-200, ease:Quint.easeOut});
break;
case 4:
TweenMax.to(grid, 1, {x:-400,y:-200, ease:Quint.easeOut});
break;
}
//        rollOver_(slideNum);
}
]]>
</fx:Script>

<s:Group width=”400″ height=”200″ horizontalCenter=”0″ verticalCenter=”0″>
<s:layout>
<s:BasicLayout clipAndEnableScrolling=”true”/>
</s:layout>
<s:TileGroup id=”grid” x=”0″ y=”0″>
<s:Rect width=”400″ height=”200″>
<s:fill>
<s:SolidColor color=”0xd54f4f”/>
</s:fill>
</s:Rect>
<s:Rect width=”400″ height=”200″>
<s:fill>
<s:SolidColor color=”0x2f977d”/>
</s:fill>
</s:Rect>
<s:Rect width=”400″ height=”200″>
<s:fill>
<s:SolidColor color=”0xfffca2″/>
</s:fill>
</s:Rect>
<s:Rect width=”400″ height=”200″>
<s:fill>
<s:SolidColor color=”0x12f0af”/>
</s:fill>
</s:Rect>
</s:TileGroup>

</s:Group>
<s:HGroup top=”20″ horizontalCenter=”0″>

<s:Button label=”1″ click=”moveGrid(1)”/>
<s:Button label=”2″ click=”moveGrid(2)”/>
<s:Button label=”3″ click=”moveGrid(3)”/>
<s:Button label=”4″ click=”moveGrid(4)”/>
</s:HGroup>

</s:Application>

GridGallery

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex 4 Cool Floating effect

This is an effect I made that looks like the components are floating free, combine with different easing effects for maximum results.

View an example here

<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
<s:Sine id=”sineEasing”
easeInFraction=”0.3″/>

<s:Move3D id=”hover1″
xFrom=”{hover1.target.x}” xBy=”5″
yFrom=”{hover1.target.y}” yBy=”25″
zFrom=”{hover1.target.z}” zBy=”10″ duration=”1800″
repeatCount=”0″ repeatBehavior=”reverse” easer=”{sineEasing}”
effectEnd=”hover1.target.alpha=1.0;”/>

<s:Move3D id=”hover2″
xFrom=”{hover2.target.x}” xBy=”5″
yFrom=”{hover2.target.y}” yBy=”25″
zFrom=”{hover2.target.z}” zBy=”10″ duration=”2400″
repeatCount=”0″ repeatBehavior=”reverse” easer=”{sineEasing}”
effectEnd=”hover2.target.alpha=1.0;”/>
</fx:Declarations>

<s:Panel title=”Floating Panel…” x=”523″ y=”208″ width=”192″ height=”201″ id=”floatPanel” creationComplete=”hover1.play([floatPanel])” horizontalCenter=”0″ verticalCenter=”0″>
<s:VGroup horizontalCenter=”0″ verticalCenter=”0″ height=”100%” verticalAlign=”middle” width=”100%” horizontalAlign=”center” contentBackgroundColor=”#6A6767″>
<s:Button label=”Button-1″ chromeColor=”#851D1D” color=”#F0F0F0″/>
<s:Button label=”Button-2″ chromeColor=”#5DB705″ color=”#3C3B3B”/>
</s:VGroup>
</s:Panel>

<s:Panel title=”Floating Panel…” x=”523″ y=”208″ width=”192″ height=”201″ id=”floatPanel2″ creationComplete=”hover2.play([floatPanel2])” horizontalCenter=”250″ verticalCenter=”110″>
<s:VGroup horizontalCenter=”0″ verticalCenter=”0″ height=”100%” verticalAlign=”middle” width=”100%” horizontalAlign=”center” contentBackgroundColor=”#6A6767″>
<mx:Text text=”This is floating with a different duration to un-sync with the other…” width=”164″ height=”117″ x=”13″/>
</s:VGroup>
</s:Panel>

Enjoy!

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Flex 3.5 Html Scrollbar control

Below I present a way to control the HTML scrollbar in order to scroll to a specific component.
I mostly use it when I deal with long repeaters or lists. The following example takes a repeater that creates groups of components, such as textAreas and buttons and places them one after the other. So by using my method you can scroll to a specific component of that list.

//Place the JavaScript Functions in your html-Template or in your webpage directly.
//CODE BELOW:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”init();callJS(Application.application.height)” height=”3500″ width=”800″ verticalScrollPolicy=”off” >

<mx:Script>
<![CDATA[
////////////// JS FUNCTIONS ////////////////////////////////////////

/* <script language=”JavaScript” type=”text/javascript”>
function getSwfSize(passedHeight)
{
theDiv = document.getElementById(“viewstack”);
theDiv.style.height = passedHeight + ‘px’;
}
</script>
*/

/* <script type=”text/javascript”>
function scrollWindow(depth)
{
var el = document.getElementById(‘viewstack’);
var c = el.clientHeight;
var total = depth;

window.scrollBy(0,(total));

}

</script>
*/
//////////////// END OF JAVASCRIPT ////////////////////////////////////////////

import flash.external.ExternalInterface;
import mx.controls.*;

var arr:Array=[1,2,3,4,5,6,7,8,9,10];

//Resizes the div in which the swf is inside. Pretty neat if you hate the flash scrollbar.
public function callJS(totalSwfHeight:Number):void
{
Application.application.height = 100+childComponent.height;
ExternalInterface.call(“getSwfSize”,(100+childComponent.height));
}

public function launchJS(str)
{
//How many pixels the scroller will move
//As the box1 is inside a repeater its id is an array that defines all the created instanses
//so we are scrolling to that instances’ y value plus a bit more to fit perfectly in the screen, not just its top.
var pointer:Number = box1[Number(str)].y+20 ;
Alert.show(“Moved Scroller at: “+String(pointer)+” px”);
//calls the scroller JavaScript function
ExternalInterface.call(“scrollWindow”,pointer);
}

//Fills the array for the repeater
public function init()
{
for(var i=0;i<=30;i++)
{
arr[i]=Number(i);
}

rep.dataProvider=arr;
}

]]&gt
</mx:Script>

<mx:Button label=”{‘GO to ‘+txtInput.text}” left=”20″ click=”launchJS(txtInput.text)”/>
<mx:TextInput id=”txtInput” left=”130″/>

<!– The VBox that contains the components –>
<mx:VBox y=”50″ x=”10″ height=”100%” id=”childComponent”>

<mx:Repeater id=”rep” count=”30″>

<mx:HBox width=”500″ y=”50″ id=”box1″>

<mx:TextArea id=”dummyTa” text=”Sample Text” selectable=”false” editable=”false” borderStyle=”none” height=”100″/>
<mx:VBox height=”100%”>
<mx:Button id=”dummyBtn” label=”Sample Button” height=”40″/>
<mx:Button id=”dummyBtn2″ label=”Sample Button” height=”40″/>
</mx:VBox>
</mx:HBox>

</mx:Repeater>

</mx:VBox>

</mx:Application>

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Tag removal AIR application for Blog posting

I was really fed up of editing my posts all the time to add “& lt” and “& gt” instead of < and > so I thought to make an air application to do just that.
So here’s the code for the tag removal tool:

<mx:Script&gt
<![CDATA[

import mx.controls.*;
import flash.filesystem.*;
import flash.events.Event;
import flash.net.FileFilter;
import flash.events.*

public var fileToOpen:File = new File();

public var fileData:String;
public var local:String=”default”;

public function opens():void
{

fileToOpen.browseForOpen(“Open”);

fileToOpen.addEventListener(Event.SELECT, fileSelected);

}

public function fileSelected(event:Event):void
{
var stream:FileStream = new FileStream();
Alert.show(String(fileToOpen.url));
stream.open(event.target as File, FileMode.READ);

fileData= stream.readUTFBytes(stream.bytesAvailable);
stream.close();

}

private function setFocusOnStart(event:Event):void
{
stage.focus=InteractiveObject(source);
}

public function localStr():String
{
if(local==”default”)
{
return source.text
}
else
{return fileData}
}

public function convertTxt(str1:String):void
{

var reg1:RegExp=/(&gt)/g;
var reg2:RegExp=/(<)/g;

str1=str1.replace(reg1,”&gt”);
//Alert.show(str1);
str1=str1.replace(reg2,”<“);

result.enabled=true;
result.text=str1;

}

function copyText(e:MouseEvent):void{

System.setClipboard(result.text);
trace(“copied: “+result.text);
Alert.show(“Text Copied!”);
}
]]&gt
</mx:Script&gt

<mx:TextArea id=”source” selectable=”true” wordWrap=”true” editable=”true” x=”76″ y=”141″ width=”252″ height=”200″ toolTip=”Source…” addedToStage=”setFocusOnStart(event)”/&gt

<mx:Button label=”Convert” fontSize=”13″ fontWeight=”bold” x=”310″ y=”91″ click=”{convertTxt(localStr());}” color=”#00BCFA” borderColor=”#00BCFA”/&gt

<mx:TextArea id=”result” x=”374″ y=”141″ width=”252″ height=”200″ editable=”true” wordWrap=”true” selectable=”true” toolTip=”Result” enabled=”false”/&gt

<mx:Label y=”11″ text=”String Converter” fontSize=”19″ fontWeight=”bold” color=”#00BCFA” fontStyle=”normal” textAlign=”center” letterSpacing=”1″ x=”244″/&gt

<mx:VRule x=”351″ y=”141″ height=”200″/&gt

<mx:Button x=”467″ y=”102″ label=”Copy to Clipboard” width=”159″ height=”31″ click=”copyText(event)” icon=”@Embed(source=’icons/copy-doc28.png’)”/&gt

<mx:Button x=”512″ y=”61″ label=”Clear Text” borderColor=”#C00000″ color=”#C00000″ click=”{local=’default’;source.text=”;source.enabled=true;result.text=”;}” icon=”@Embed(source=’icons/minus-white28.png’)”/&gt

<mx:Button x=”76″ y=”105″ label=”Browse…” click=”{local=’1′;opens();source.text=’\n’+’FILE SELECTED’;source.enabled=false;}” icon=”@Embed(source=’icons/folder28.png’)”/&gt

Facebooktwittergoogle_pluspinterestlinkedin
linkedin

Create/Edit XML with Flex and PHP (part 2/2)

This is the second part of the Flex-PHP-XML tutorial, in which I’ll show you how to delete nodes from an XML and thus making it work like a database.

  • First we need to have something in our XML so lets assume the following content:
  • <?xml version=”1.0″ encoding=”UTF-8″?&gt
    <music&gt
    <newItemID&gt
    <titleID>very soon.mp3</titleID&gt
    <urlID>http://www.filerecycle/music/very soon.mp3</urlID&gt
    <dateID>9/8/2009</dateID&gt
    <descriptionID>delete fodder…</descriptionID&gt
    </newItemID&gt
    <newItemID id=”2625″&gt
    <titleID>id.mp3</titleID&gt
    <urlID>http://www.filerecycle/music/id.mp3</urlID&gt
    <dateID>10/8/2009</dateID&gt
    <descriptionID>song?</descriptionID&gt
    </newItemID&gt
    </music&gt

  • Now some MXML for the call to PHP
  • <mx:Button label=”Remove Item from List” width=”150″ height=”50″ top=”150″ styleName=”ButtonRem” click=”filePop();” horizontalCenter=”180″ fontSize=”10″ fontWeight=”bold”/&gt

  • and the HTTP Service Request assuming a datagrid named “infoMus” which holds our data from the XML:
  • <mx:HTTPService id=”filePop” showBusyCursor=”true” url=”assets/xmlRemover.php” headers=”null” requestTimeout=”18″ resultFormat=”e4x”
    contentType=”application/x-www-form-urlencoded” method=”GET” result=”resultHandle(event)”>
    <mx:request>
    <id>{infoMus.selectedItem.id}</id&gt
    </mx:request&gt
    </mx:HTTPService&gt

  • And finally the PHP code that does the heavy lifting:
  • <?php
    $file=”music.xml”;
    $xml=simplexml_load_file($file) or die (“Unable to load XML”);

    $keyToKill = null;

    $counter = 0;
    foreach ( $xml->newItemID as $node => $nodeObject)
    {
    $attr = $nodeObject->attributes();

    if ( $attr[‘id’] == $_GET[‘id’])
    {
    $itemToKill = $counter;
    break;
    }
    ++$counter;
    }
    echo “Key that will be removed:{$_GET[‘id’]}|{$itemToKill}”;
    unset($xml->newItemID[$itemToKill]);

    $doc = new DOMDocument(‘1.0’);
    $doc->loadXML( $xml->asXML());
    $doc->preserveWhiteSpace = false;
    $doc->formatOutput = true;
    file_put_contents( $file, $doc->saveXML());
    ?&gt

    Facebooktwittergoogle_pluspinterestlinkedin
    linkedin