Flashguy’s Blog
Wicked Actionscript

I am now Director of Technology at Deisgnit Munich

December 2nd, 2011 by Gabor Wraight

Designit

11 years of freelancing come to an end. I finally made a big decision and signed my contract with Designit yesterday.

I am now the Director of Technology at the Munich office.

As I’ve been working for Designit almost a year now, I already know the whole German Team and am now looking forward to get to know all other zoo members.

This means no more time for freelance jobs. I already changed my linkedin and xing profile so I hope the ammount of job applications will decrease drastically.

I will keep this Blog and continue to keep you updated on intersting facts and code snippets.

Posted in Work | No Comments »

Detect device orientation through Accelerometer Data

March 27th, 2011 by Gabor Wraight

Update: Thanks to a comment from Boris calling preventDefault() on a StageOrientationEvent will give you the orientation without the stage reorientating.

In a current project, I had to set autoOrients to false to lock the screen orientation on a mobile app. Unfortunatly by doing this, StageOrientationEvent.ORIENTATION_CHANGE doesn’t work anymore. This is how you can still detect the current rotation using the accelerometer data:

var accel:Accelerometer = new Accelerometer();
accel.addEventListener(AccelerometerEvent.UPDATE, onAccelUpdate);

function onAccelUpdate(e:AccelerometerEvent):void
{          
    var myConst:Number = Math.sin(Math.PI/4);
    if(e.accelerationX > 0 && e.accelerationY > -myConst && e.accelerationY < myConst){
        trace("left");
    }else if( e.accelerationY >= myConst){
        trace("default");
    }else if(e.accelerationX < 0 && e.accelerationY > -myConst && e.accelerationY < myConst){
        trace("right");
    }else if(e.accelerationY <= myConst){
        trace("upside down");
    }      
}

Posted in AIR Mobile, Android, iOs | 4 Comments »

localisation token generator

September 9th, 2010 by Gabor Wraight

Almost every day, I come across a procedure which I find really anoying.
As a Flexdeveloper, you get your artwork delivered from a designer. Today, we have Flash Catalyst, which really imporves the workflow. I’m so happy to have it.

What I do is save a Flexproject from Catalyst, import it to Flex and start adding the logic. Great! Now what really bugged me, was localization. I had to copy the Text from each RichTextComponent to a xml file. After that, I had to add the resourceManager.getString() function where the Text previously was. In views with lots of text, this took ages.

So I came up with a neet little AIR App called “localisation token generator”.

What it does is exactly what I described above, only a lot faster. Let me explain in detail:

You start off with a Photoshop File like this (maybe a little more pretty):

You import this file into Flash Catalyst and get this:

<?xml version='1.0' encoding='UTF-8'?>
<s:Application xmlns:d="http://ns.adobe.com/fxg/2008/dt" xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" width="800" height="600" backgroundColor="#FFFFFF" preloaderChromeColor="#FFFFFF">
    <fx:Style source="Main.css"/>
    <s:BitmapImage smooth="true" source="@Embed('/assets/images/artwork/Background.png')" d:userLabel="Background" x="0" y="0"/>
    <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" kerning="off" lineHeight="214.3%" d:userLabel="My Text Number 1" whiteSpaceCollapse="preserve" x="69" y="67">
        <s:content><s:p><s:span>My Text Number 1</s:span></s:p></s:content>
    </s:RichText>
    <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" kerning="off" lineHeight="214.3%" d:userLabel="More Text" whiteSpaceCollapse="preserve" x="68" y="111">
        <s:content><s:p><s:span>More Text</s:span></s:p></s:content>
    </s:RichText>
    <s:RichText color="#FEFEFE" fontFamily="News Gothic Std" fontSize="14" height="208" kerning="off" lineHeight="214.3%" d:userLabel="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed di" whiteSpaceCollapse="preserve" width="576" x="70" y="165">
        <s:text>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</s:text>
    </s:RichText>
</s:Application>

Now you start up “localisation token generator” and first of all click on “Save required Files” to get a proper xml file for the tokens and the tokensVo.as. Save these files in the src folder of your Flex Project.

Now you first drag the MXML File containing your Code onto the Target MXML Drop Target
Next, drag the tokens.xml file from your src Folder onto the Target XML Drop Target. After doing this, you will have the opportunity to choose your target language. Also a Token Prefix is generated from the mxml’s filename. If you don’t like it, just change it.

Now click on “Generate Tokens” and enjoy! Be sure to have a backup of your files, just in case.

What you will end up will look like this:

<s:Application width="800" height="600"
              backgroundColor="#FFFFFF" preloaderChromeColor="#FFFFFF"
              xmlns:d="http://ns.adobe.com/fxg/2008/dt"
              xmlns:fx="http://ns.adobe.com/mxml/2009"
              xmlns:s="library://ns.adobe.com/flex/spark">    
  <fx:Style source="Main.css"/>  
  <s:BitmapImage smooth="true" source="@Embed('/assets/images/artwork/Background.png')" d:userLabel="Background" x="0" y="0"/>
  <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" kerning="off" lineHeight="214.3%" d:userLabel="My Text Number 1" whiteSpaceCollapse="preserve" x="69" y="67">
    <s:content>{TextFlowUtil.importFromString(resourceManager.getString('tokens','Main_MyTextNumber1_1'))}</s:content>
  </s:RichText>
  <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" kerning="off" lineHeight="214.3%" d:userLabel="More Text" whiteSpaceCollapse="preserve" x="68" y="111">
    <s:content>{TextFlowUtil.importFromString(resourceManager.getString('tokens','Main_MoreText_2'))}</s:content>
  </s:RichText>
  <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" height="208" kerning="off" lineHeight="214.3%" d:userLabel="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed di" whiteSpaceCollapse="preserve" width="576" x="70" y="165">
    <s:content>{TextFlowUtil.importFromString(resourceManager.getString('tokens','Main_Loremipsumdolor_3'))}</s:content>
  </s:RichText>
</s:Application>

To get the localisation work, just add some script so your file looks like this:

<s:Application width="800" height="600" creationComplete="application1_creationCompleteHandler(event)"
              backgroundColor="#FFFFFF" preloaderChromeColor="#FFFFFF"
              xmlns:d="http://ns.adobe.com/fxg/2008/dt"
              xmlns:fx="http://ns.adobe.com/mxml/2009"
              xmlns:s="library://ns.adobe.com/flex/spark">
   
  <fx:Style source="Main.css"/>
   
  <fx:Script>
      <![CDATA[
         import mx.events.FlexEvent;
         import mx.resources.ResourceBundle;
         import mx.resources.ResourceManager;
         
         import spark.utils.TextFlowUtil;
         
         private var locales:Array;
         public var TokenData:XML;
         
         protected function application1_creationCompleteHandler(event:FlexEvent):void
         {
             var urlLoader:URLLoader = new URLLoader();
             urlLoader.addEventListener(Event.COMPLETE, parseTokens);
             urlLoader.load(new URLRequest('tokens.xml'));
         }
         
         private function parseTokens(e:Event):void
         {              
             var key:XML;
             var tokenList:XMLList = new XML( e.target.data )..token;
             var languages:XMLList = new XML( e.target.data )..language;
             
             locales = new Array();    
             
             // Tokens
             for(var i:int = 0; i < languages.length(); i++){
                 var tokenResource:ResourceBundle = new ResourceBundle(languages[i], 'tokens');
                 for each(key in tokenList)
                 {
                     tokenResource.content[key.@name] = new TokenVo(key.@name, key[languages[i].@id], languages[i]);
                     
                 }            
                 ResourceManager.getInstance().addResourceBundle(tokenResource);    
                 locales.push(languages[i])
             }              
             
             ResourceManager.getInstance().localeChain = locales;              
             ResourceManager.getInstance().localeChain = ["en_UK"];    
             
         }

     ]]>
  </fx:Script>
  <s:BitmapImage smooth="true" source="@Embed('/assets/images/artwork/Background.png')" d:userLabel="Background" x="0" y="0"/>
  <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" kerning="off" lineHeight="214.3%" d:userLabel="My Text Number 1" whiteSpaceCollapse="preserve" x="69" y="67">
    <s:content>{TextFlowUtil.importFromString(resourceManager.getString('tokens','Main_MyTextNumber1_1'))}</s:content>
  </s:RichText>
  <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" kerning="off" lineHeight="214.3%" d:userLabel="More Text" whiteSpaceCollapse="preserve" x="68" y="111">
    <s:content>{TextFlowUtil.importFromString(resourceManager.getString('tokens','Main_MoreText_2'))}</s:content>
  </s:RichText>
  <s:RichText color="#fefefe" fontFamily="News Gothic Std" fontSize="14" height="208" kerning="off" lineHeight="214.3%" d:userLabel="Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed di" whiteSpaceCollapse="preserve" width="576" x="70" y="165">
    <s:content>{TextFlowUtil.importFromString(resourceManager.getString('tokens','Main_Loremipsumdolor_3'))}</s:content>
  </s:RichText>
</s:Application>

What you have now is a fully functional localized Flex Application.

Hope this saves some time for you. Click on the Badge to install the Application.

Please upgrade your Flash Player This is the content that would be shown if the user does not have Flash Player 9.0.115 or higher installed.

Posted in AIR, Flash Catalyst, Flashbuilder | 1 Comment »

Custom Timer Class with pause functionality

August 18th, 2010 by Gabor Wraight

In my current Project I came across an issue that bugged me for a while.

The thing is, I’m building a game where a timer is used to jump to the next level(e.g. every 30 seconds the level goes one up). Unfortunatly, the game has a pause mode if you press “p” on the keyboard. I needed to pause and not stop the leveltimer, to be able to continue with the time left in the current cycle. Otherwise you could easily cheat by pausing the game just before you get to the next level. If you would start the normal timer again, you would again have 30 seconds untill the next level.

So here’s what I came up with:

package de.rockbox.utils
{

import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;

public class RBTimer extends Timer
{
private var initDelay:Number;
private var startTime:int;
private var timeLeftCurrentCicle:int;

public function RBTimer(delay:Number, repeatCount:int=0)
{
super(delay, repeatCount);

// save the initial delay for later use
initDelay = delay;

// save start time to calculate leftover time when paused
startTime = getTimer();

// listener to reset the delay to its initial value
addEventListener(TimerEvent.TIMER,onTimer);
}

private function onTimer(event:TimerEvent):void
{
// reset the delay to ist initial value
delay = initDelay;

// reset &amp; save start time to calculate leftover time when paused
startTime = getTimer();
}

public function togglePause():void
{
// toggle pause
if(running){
// get the current time
var timeNow:int = getTimer();

// calculate the elapsed time since the timer was started
var elapsed:int = timeNow - startTime;

// calculate the time left in the current ccle
timeLeftCurrentCicle = delay - elapsed;

// stop the timer
stop();

// set delay to the time left in the current cycle
delay = timeLeftCurrentCicle;
}else{
// reset &amp; save start time to calculate leftover time when paused
startTime = getTimer();

// start the timer with the new delay
// as soon as TimerEvent.Timer is dispatched,
// the delay is reset to its initial value.
start();
}
}
}
}

Use this class just like the standard timer class:

var timer:RBTimer = new RBTimer(1000);
timer.start();

// to toggle pause
timer.togglePause();

Posted in Actionscript 3.0 | No Comments »

New Web2Print Job

August 12th, 2010 by Gabor Wraight

Designskins.com

Designskins.com is a website which lets you choose from a large list of devices such as your mobile phone. You can then customize a skin for your device using images from the gallery or even upload custom images. Add text and some icons and send your skin to the cart. The server then generates a pre-press concidering all the elements on your skin. The guys from designskins then print your skin on their very own foil. As soon as you get your skin via post, you just stick it onto your device and show off in front of your friends.

The Project is built entirely in Flashbuider(Flex) using only state of the art techniques. Feel free to check it out and play with them.

Posted in Actionscript 3.0, Flashbuilder, Flex, Work | 2 Comments »

New Office

July 7th, 2010 by Gabor Wraight

Last Thursday we moved into our fabulous new office.

You can now find me at:

Deisenhofener Straße 1
D-81539 München
co Hello AG

+49 178 2441939
+49 89 244163391

Looking forward to seeing you…

Posted in Work | 1 Comment »

Flashbuilder – setting Text in the Richtext Component

March 16th, 2010 by Gabor Wraight

Just to file this for myself. Peter deHaan wrote this great Post on the many different ways of setting text in a spark RichText Component.
Check it out here.

My favourite is getting HTML Markup from a String into the RichText Component. Perfect for localisation.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/08/11/setting-text-in-a-spark-richtext-control-in-flex-4/ -->
<s:Application name="Spark_RichText_text_test"
       xmlns:fx="http://ns.adobe.com/mxml/2009"
       xmlns:s="library://ns.adobe.com/flex/spark"
       xmlns:mx="library://ns.adobe.com/flex/halo">
 
    <fx:Script>
        <![CDATA[
           import spark.utils.TextFlowUtil;
       ]]>
    </fx:Script>
 
    <fx:Declarations>
        <fx:String id="htmlTextAsMarkup"><![CDATA[<p>The quick brown <span fontWeight="bold">fox jumps over</span> the lazy dogg.</p>]]></fx:String>
    </fx:Declarations>
 
    <s:RichText id="richTxt"
           textFlow="{TextFlowUtil.importFromString(htmlTextAsMarkup)}"
           horizontalCenter="0" verticalCenter="0" />
 
</s:Application>

By the way, you should definitely bookmark his Blog. It’s my best resource on Flashbuilder and Flex Examples.

Posted in Flashbuilder | No Comments »

Getting a “Shake” Event on the iPhone with Flash CS5

February 8th, 2010 by Gabor Wraight

If you need to find out if a User shakes his iPhone the following might help:

var accel:Accelerometer = new Accelerometer();
accel.addEventListener(AccelerometerEvent.UPDATE, onAccelUpdate);

var lastAccelX:Number;
var lastAccelY:Number;
var lastAccelZ:Number;

var shaked:Boolean;
var shakeTreshhold: Number = 1.5

function onAccelUpdate(e:AccelerometerEvent):void
{
    if ((e.accelerationX - lastAccelX > shakeTreshhold)||(e.accelerationY - lastAccelY > shakeTreshhold)||(e.accelerationZ - lastAccelZ > shakeTreshhold))
    {
        if(shaked)
            return;
           
        shaked = true;
        // do your shake action here!!!

        var t:Timer = new Timer(800, 1);
        t.addEventListener(TimerEvent.TIMER, function onTimer():void{
            shaked = false;
        });
        t.start();
    }
   
    lastAccelX = e.accelerationX;
    lastAccelY = e.accelerationY;
    lastAccelZ = e.accelerationZ;
}

What I do here is listen for accelerometer update Events and compare the values from the last with the current Event. If the delta is higher than the defined treshold value, the phone is shaken. To avoid to many shakes after another I set a timer. I’m not sure, if this is the best practice for doing this, but it works out well in my App.

Posted in Flash CS5, iphone | 7 Comments »

Determining the direction of a Gesture in Flash CS5 on the iPhone

February 5th, 2010 by Gabor Wraight

If you need to find out in what direction a gesture goes, e.g. Up, Down, Left or Right the following Script might help.

this.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin)
this.addEventListener(TouchEvent.TOUCH_END, onTouchEnd)

var startPoint:Point;
var endPoint:Point;

function onTouchBegin(e:TouchEvent):void
{
    startPoint = new Point(e.localX, e.localY);
}
function onTouchEnd(e:TouchEvent):void
{
    endPoint = new Point(e.localX, e.localY);
    var a:Number = endPoint.y - startPoint.y;
    var b:Number = endPoint.x - startPoint.x;
   
    if(a*a > b*b){
        if(a > 0){
            //down
        }else{
            //up
        }
    }else{
        if(b > 0){
            //right
        }else{
            //left
        }
    }
}

Posted in Actionscript 3.0, Flash CS5, iphone | No Comments »

Adding a hyperlink to a Flashbuilder RichText Component

January 23rd, 2010 by Gabor Wraight

First of all be aware to use RichEditableText instead of the RichText. Unfortunatly I couldn’t get links to work in the RichText Component. Also set editable=”false” focusEnabled=”false” in the RichEditableText Component to make it clickable

<s:RichEditableText editable="false" focusEnabled="false" >
    <s:content><s:p><s:span>some Text</s:span><s:a href="http://www.flashguy.de">the link</s:a><s:span>more Text</s:span></s:p></s:content>
</s:RichEditableText>

Posted in Actionscript 3.0, Flashbuilder, Flex | No Comments »

« Previous Entries