<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ben Snider</title>
	<atom:link href="http://www.bensnider.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bensnider.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 02 Mar 2010 02:23:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Lice Helper Launched</title>
		<link>http://www.bensnider.com/2010/03/01/lice-helper-launched/</link>
		<comments>http://www.bensnider.com/2010/03/01/lice-helper-launched/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 02:23:49 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[CakePHP]]></category>
		<category><![CDATA[Portfolio]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=174</guid>
		<description><![CDATA[Recently finished and launched a new website for a client. The website advertises a lice removal service and provides means for potential customers to learn about the service and get in touch with the business quickly and easily.
Lice Helper
The site is built on a CakePHP application and actually uses Wordpress for the blog section of [...]]]></description>
			<content:encoded><![CDATA[<p>Recently finished and launched a new website for a client. The website advertises a lice removal service and provides means for potential customers to learn about the service and get in touch with the business quickly and easily.<br />
<a href="http://www.licehelper.com/">Lice Helper</a></p>
<p>The site is built on a CakePHP application and actually uses Wordpress for the blog section of the site. It doesn&#8217;t use Wordpress for any of the front end, but in the back end the standard Wordpress Dashboard is used to manage, edit, and write blog posts that are then displayed in the front end blog section.</p>
<p>The site also utilizes my meta description and title components, that allow the application to manage those parts of the page independently of the page content. Basically it just ties a URL to a title or a description, matches them up when pages are requested, and if it finds a matching record it outputs it in the proper place. Otherwise it will output a sensible default text.</p>
<p>I did enjoy working with CakePHP again as it&#8217;s been some time. But all the things I liked about it still apply. It&#8217;s still lightening fast from prototype to finished site, and design modifications couldn&#8217;t be any simpler. All in all, good project, and I think the end result looks and works very well.</p>
<p><a href="http://www.licehelper.com"><img class="aligncenter" title="Lice Helper" src="http://media.bensnider.com/images/lice_helper.png" alt="Lice Helper" width="600" height="468" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/03/01/lice-helper-launched/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ImageMagick Split and Join a Sprite Sheet</title>
		<link>http://www.bensnider.com/2010/02/09/imagemagick-split-and-join-a-sprite-sheet/</link>
		<comments>http://www.bensnider.com/2010/02/09/imagemagick-split-and-join-a-sprite-sheet/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 23:03:39 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Game Dev]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Shell Scripting]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=154</guid>
		<description><![CDATA[Continuing the Flixel theme that seems to be brewing here, I found a good way to transform images from full dimension art to sprite sheets. This is useful when converting an image into a sheet compatible with the Flixel tile and map system. In my case I am using it to split up background images [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing the <a href="http://wiki.github.com/AdamAtomic/flixel/">Flixel</a> theme that seems to be brewing here, I found a good way to transform images from full dimension art to sprite sheets. This is useful when converting an image into a sheet compatible with the Flixel tile and map system. In my case I am using it to split up background images so I can use them in <a href="http://www.tbam.com.ar/utility--flan.php">Flan</a>, the Flixel map editor.</p>
<p>I&#8217;m just using the standard <a href="http://www.imagemagick.org/script/index.php">ImageMagick</a> tools <em><a href="http://www.imagemagick.org/script/convert.php">convert</a></em> and <em><a href="http://www.imagemagick.org/script/montage.php">montage</a></em> to split and join the images, as well as some bash-fu to sort files properly. I am using <a href="http://www.cygwin.com/">Cygwin</a> to get bash tools on my Windows machine.</p>
<p>The first command is used to split up the main image. The only constraints here are that the resulting tiles must be square, and that they don&#8217;t exceed the width limit for Flash <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html">BitmapData</a> objects. So here we simply are cropping the image into square tiles.</p>
<pre class="prettyprint">convert full.png -crop 32x32 tiles.png</pre>
<p>&nbsp;<br />
This will spit out a bunch of images in the current folder named tiles-%d.png where %d is the 0 based index of the tile. This also assumes that the width and height of the full.png image are divisible by 32 without remainder.</p>
<p>The next command we need is to stitch the images back together. For this we will use the handy <em>montage</em> tool to tile the images into one big sheet. We just pass it a sorted list of names and tell it to make 1 row with as many columns as it needs (the x1 parameter). Sorting is not entirely necessary but using the default bash globbed format will result in tiles that should be at the end of the image randomly at the beginning (try it before this step by noting the output of `ls tiles*.png`).</p>
<pre class="prettyprint">files=$(ls tiles*.png | sort -t '-' -n -k 2 | tr '\n' ' ')
montage $files -tile x1 -geometry 32x32+0+0 sheet.png</pre>
<p>&nbsp;<br />
If all went well we should see, inside the current directory, an image with all of our separate tile sprites in a single row in order from the original image from left to right and top to bottom.</p>
<p>This technique is also useful for converting &#8220;liberated&#8221; sprite sheets that have more than one row, into single row sprite sheets that flixel can handle out of the box.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/02/09/imagemagick-split-and-join-a-sprite-sheet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flixel Pixel Perfect Collisions</title>
		<link>http://www.bensnider.com/2010/01/31/flixel-pixel-perfect-collisions/</link>
		<comments>http://www.bensnider.com/2010/01/31/flixel-pixel-perfect-collisions/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 04:13:26 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Game Dev]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=134</guid>
		<description><![CDATA[I haven&#8217;t found a decent source of information about this on the interwebs so I thought I&#8217;d share my findings. Flixel doesn&#8217;t have any built in pixel perfect collision support, it just assumes that you are using square (or at least rectangle) sprites and don&#8217;t use any rotation. Well, that&#8217;s not entirely a real world [...]]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t found a decent source of information about this on the interwebs so I thought I&#8217;d share my findings. Flixel doesn&#8217;t have any built in pixel perfect collision support, it just assumes that you are using square (or at least rectangle) sprites and don&#8217;t use any rotation. Well, that&#8217;s not entirely a real world assumption so some of us will have to dig around and implement something ourselves. Hence, the below class.</p>
<p>The class I developed is a simple override of the base FlxSprite class with some modifications to its collision detection system. It takes advantage of the fact that each sprite has its own set of BitmapData in its own coordinate space, which the framework uses to blit to the main screen <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html">BitmapData</a>. BitmapData objects in Flash provide us with a native implementation (in the Player AFAIK) of per pixel collision detection, using the <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html#hitTest%28%29">hitTest</a> method.</p>
<p>The hitTest method takes 5 parameters, but we only really care about the first 4. The first parameter we pass it defines where the calling BitmapData object is in screen space, i.e. the sprite&#8217;s (x,y) coordinates. We then pass it a threshold alpha value, 0 being transparent and 255 being opaque. If you want semi-transparent regions of your sprite to collide then set this to something lower than 255 (0xFF is the hexadecimal representation of decimal 255). The third parameter is the colliding sprite&#8217;s BitmapData object. And the fourth is the colliding sprite&#8217;s (x,y) coordinates in screen space.</p>
<p>I have abstracted this into the class&#8217;s structure, so the overridden functions handle everything. You can use another alpha threshold by setting the sprite&#8217;s <em>alphaThreshold</em> value to something valid, as explained above. You can also disable this pixel perfect collision detection method per technique by either setting <em>doPerfectCollide</em> or <em>doPerfectOverlap</em> to false. Because there are two methods Flixel uses to detect collisions, the class implements enhanced versions of both, and allows you to disable either independently.</p>
<p>Note that, in order for the collision detection to be pixel perfect, either a) both colliding objects must subclass PPlxSprite or b) the sprite calling <em>overlaps</em> or <em>collide</em> must sublcass PPlxSprite and the colliding sprite must have a single frame. This is due to fact that the original FlxSprite class does not expose the <em>_framePixels</em> BitmapData object which is needed to collide the objects with the frame that is currently displayed. When a FlxSprite is collided with a PPlxSprite and the perfect collision is enabled, the exposed <em>_pixels</em> BitmapData is used, which contains the entire sprite sheet, so collisions are detected against all frames, not just the frame displayed. However, changing existing sprite&#8217;s to use this class is easy enough so as not to cause problems.</p>
<p>Note also that we only call the hitTest method when we know there is already a bounding box collision, so as not to waste CPU cycles. The native hitTest method is fast but probably not fast enough to call every frame, which would be wasteful in any case.</p>
<p>Below is the PPlxSprite class which override the collision methods to provide pixel perfect collisions.</p>
<pre class="prettyprint">import flash.display.BitmapData;
import flash.geom.Point;

import org.flixel.FlxCore;
import org.flixel.FlxSprite;

public class PPlxSprite extends FlxSprite {

    public var alphaThreshold:uint = 0xFF;
    public var doPerfectOverlap:Boolean = true;
    public var doPerfectCollide:Boolean = true;

    protected var _corePos:Point = new Point();
    protected var _thisPos:Point = new Point();

    public function PPlxSprite(X:int=0, Y:int=0, SimpleGraphic:Class=null) {
        super(X, Y, SimpleGraphic);
    }

    public function get framePixels():BitmapData { return this._framePixels; }

    override public function overlaps(Core:FlxCore):Boolean {
        var doesOverlap:Boolean = super.overlaps(Core);
        if (doesOverlap &#038;&#038; this.doPerfectOverlap &#038;&#038; Core is FlxSprite) {
            doesOverlap = this.perfectCollision(FlxSprite(Core));
        }
        return doesOverlap;
    }

    public function perfectCollision(Sprite:FlxSprite):Boolean {
        this._corePos = Sprite.getScreenXY(this._corePos);
        this._thisPos = this.getScreenXY(this._thisPos);

        var corePixels:BitmapData;
        if (Sprite is PPlxSprite) {
            corePixels = PPlxSprite(Sprite).framePixels;
        } else {
            // i guess other standard FlxSprites are boned if they are animted
            corePixels = Sprite.pixels;
        }

        return this._framePixels.hitTest(this._thisPos, this.alphaThreshold, corePixels, this._corePos);
    }

    override public function hitWall(Contact:FlxCore=null):Boolean { return this.hitSomething(Contact); }
    override public function hitFloor(Contact:FlxCore=null):Boolean { return this.hitSomething(Contact); }
    override public function hitCeiling(Contact:FlxCore=null):Boolean { return this.hitSomething(Contact); }

    public function hitSomething(Contact:FlxCore):Boolean {
        var didHit:Boolean = true;
        if (this.doPerfectCollide &#038;&#038; Contact is FlxSprite) {
            didHit = this.perfectCollision(FlxSprite(Contact));
        }

        return didHit;
    }
}</pre>
<p>&nbsp;<br />
Here I have overriden the core FlxSprite methods that are responsible for collision detection, those methods being overlaps and the hit family of methods. Overlaps gets called when you explicitly issue a sprite.overlaps(otherSprite); This is a simple override that adds functionality to the super overlaps method, namely, calling the pixel perfect detection method and returning its results.</p>
<p>The hit family of methods are called after calling the collide family of methods, including collideArray and the like. The collide methods, when they have detecting a bounding box collision, call the hit family of methods, depending on the location of the collision, which return a boolean. If the called hit method implemented by the sprite returns false, the collide method aborts and reports that it didn&#8217;t collide after all. This is the behavior on which the above hit methods rely, and return false when it detects that while a bounding box collision may have occurred, the pixels in either sprite have not collided.</p>
<p>A short usage class follows.</p>
<pre class="prettyprint">public class SomeSprite extends PPlxSprite {

    // Embed sprite image.

    public function SomeSprite(X:Number, Y:Number):void {
        super(X, Y);
        // Load sprite image, and other sprite stuff
    }

    override public function hitWall(Contact:FlxCore):Boolean {
        if (super.hitWall(Contact)) {
            this.hurt(1);
            return true;
        }
        return false;
    }
}</pre>
<p>&nbsp;<br />
Here, all we do is simply extend the PPlxSprite class from above, and do what we normally do for sprites. We also decide to do something special when a character hits a wall, namely, get hut. To do this we override the hitWall method, call the super hitWall (which would be the PPlxSprite hitWall) method, and depending on its return value, we either get hurt or do nothing. We don&#8217;t need to do anything special for calling the overlaps method, as this will simply call PPlxSprite overlaps method.</p>
<p>So, hopefully this is helpful for someone looking to do this, or at least someone can find the ideas listed here useful. Let me know if you used it and if you find any bugs, improvements, or have any other suggestions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/01/31/flixel-pixel-perfect-collisions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flixel Puddles and Oil Slicks</title>
		<link>http://www.bensnider.com/2010/01/18/flixel-puddles-and-oil-slicks/</link>
		<comments>http://www.bensnider.com/2010/01/18/flixel-puddles-and-oil-slicks/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 22:46:35 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=122</guid>
		<description><![CDATA[I&#8217;ve been using the super cool Flixel framework to make a game and it&#8217;s quite handy for most things. The game I&#8217;m working on is basically a top down&#8230;ehh, well let&#8217;s just say it&#8217;s top down.   I can post more details when the game is actually released.
As a category, top down and platformer [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using the super cool <a target="_blank" href="http://wiki.github.com/AdamAtomic/flixel/">Flixel</a> framework to make a game and it&#8217;s quite handy for most things. The game I&#8217;m working on is basically a top down&#8230;ehh, well let&#8217;s just say it&#8217;s top down. <img src='http://www.bensnider.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I can post more details when the game is actually released.</p>
<p>As a category, top down and platformer games in general usually have some type of movement modification obstacles. These obstacles allow the player to pass through them, so they don&#8217;t stop the player from moving, but they somehow alter the player&#8217;s course by speeding up, slowing down, or sending the player in a different direction. In my case, these obstacles are oil slicks and water puddles, which speed up and slow down the player in whatever direction they are traveling. Here I will cover how I solved speeding up and slowing down the player when he crosses over such an obstacle.</p>
<p>Below is a skeleton of my main player class:</p>
<pre class="prettyprint"> package sprites {
	import org.flixel.FlxG;
	import org.flixel.FlxSprite;

	public class Player extends FlxSprite {

		[Embed(source="player.png")] private var Img:Class;

		protected var _runSpeed:Number = 100;

		public var velocityFactor:Number = 1;

		public function Girl(X:int=0, Y:int=0) {
			super(Img, X, Y, true, false, 58, 58);

			drag.x = this._runSpeed * 8;
			drag.y = this._runSpeed * 8;

			maxVelocity.x = this._runSpeed;
			maxVelocity.y = this._runSpeed;

			...
		}

		override public function update():void {
			// MOVEMENT
			acceleration.x = acceleration.y = 0;
			this.maxVelocity.x = this._runSpeed * this.velocityFactor;
			this.maxVelocity.y = this._runSpeed * this.velocityFactor;
			if (FlxG.keys.UP) {
				acceleration.y -= drag.y;
			}
			// And similarly for all 4 key directions
			...

			super.update();
		}
	}
}</pre>
<p>Using this player class, we can see that by modifying the velocityFactor instance variable, we can effectively control how fast the player can move around the screen. By setting velocityFactor equal to a value less than one, we decrease the player speed, and by setting it equal to a value greater than one we increase the player speed. So what we need now is a way to modify this value externally in response to player interaction with the world, namely, the player stepping onto a puddle or an oil slick. We also need sprites that define how they should change the player movement when they are stepped over.</p>
<p>Below is a skeleton of one of my obstacle classes:</p>
<pre class="prettyprint">package sprites.obstacles {
	import org.flixel.FlxG;
	import org.flixel.FlxSprite;

	public class SpawnerObstacle extends FlxSprite {

		public function get playerVelocityFactor():Number { return 2; }

		[Embed(source="spawner.png")] private var SpawnerImg:Class;

		public function SpawnerObstacle(X:int=0, Y:int=0) {
			super(SpawnerImg, X, Y, true, false, 24, 24);

			this.fixed = true;
		}

	}
}</pre>
<p>Here is just a simple implementation of a FlxSprite class where we define that this sprite, when stepped over, speeds up the player by a factor of 2.</p>
<p>Below are the relevant parts of the update() method in my main PlayState class.</p>
<pre class="prettyprint">this._player.velocityFactor = 1;
for each (sprite in this._obstacles) {
	if (this._player.overlaps(sprite)) {
		trace('modifying player velocity');
		this._player.velocityFactor = obstacle.playerVelocityFactor;
		break;
	}
}</pre>
<p>Here we loop over the obstacle sprites in the _obstacles array. This array would be created whenever you initialize the obstacles for the game. The obstacles themselves, in this case, are instances like the above SpawnerObstacle class, which have a playerVelocityFactor getter attached. In the beginning, we make sure that we set the player&#8217;s velocityFactor to 1 so that the player moves at the default speed in the case that they are not on top of an obstacle sprite. We also break out of the loop when we collide with a single obstacle sprite to avoid any extra complexity. We could make it so that we average the velocity factors when multiple obstacle sprites are encountered, but I don&#8217;t have this use case so it would be unnecessary.</p>
<p>When all these parts are in place and working in conjunction, we have a game that satisfies our original goal. When the player collides with one of our obstacles sprites, he is either sped up or slowed down, depending on the velocity factor defined by the colliding sprite. If I get any less lazy (highly unlikely) I&#8217;ll post an example swf with source code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/01/18/flixel-puddles-and-oil-slicks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Computer Engineer Barbie</title>
		<link>http://www.bensnider.com/2010/01/13/computer-engineer-barbie/</link>
		<comments>http://www.bensnider.com/2010/01/13/computer-engineer-barbie/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 22:10:55 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[barbie]]></category>
		<category><![CDATA[funny]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=111</guid>
		<description><![CDATA[A coworker writes me saying:
Please take a moment to vote for Barbie to become a Computer Engineer.  Future generations of computer engineers would really appreciate it if we could influence some girls to take up the profession.
So indeed, I did vote, and so should you&#8230;.or else! From the Barbie site:
Computer engineers have lots of [...]]]></description>
			<content:encoded><![CDATA[<p>A coworker writes me saying:</p>
<blockquote><p>Please take a moment to vote for Barbie to become a Computer Engineer.  Future generations of computer engineers would really appreciate it if we could influence some girls to take up the profession.</p></blockquote>
<p>So indeed, I did vote, and so should you&#8230;.or else! From the Barbie site:</p>
<blockquote><p>Computer engineers have lots of different specialties. They can do anything from building computers to making video games!</p></blockquote>
<div>
<img style="float: right; margin-right: 5em; margin-left: 5em; border: black solid 1px;" src="http://media.bensnider.com/images/engie_barbie.jpg" alt="Computer Engineer Barbie"/></p>
<p>
It&#8217;s true folks. Why would any young girl not want a computer engineer Barbie? It&#8217;s fun for the whole family! I certainly wish my toys could program an <a href="http://en.wikipedia.org/wiki/Analog_synthesizer">analog synthesizer</a>.</p>
<p><a href="http://www.barbie.com/vote/">Vote!</a>
</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/01/13/computer-engineer-barbie/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flash Draw Transparent BitmapData</title>
		<link>http://www.bensnider.com/2010/01/12/flash-draw-transparent-bitmapdata/</link>
		<comments>http://www.bensnider.com/2010/01/12/flash-draw-transparent-bitmapdata/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 15:17:14 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[bitmapdata]]></category>
		<category><![CDATA[transparent]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=105</guid>
		<description><![CDATA[Recently ran into an issue where I thought I should have been drawing a transparent BitmapData object, but the resulting object had a white background. The original incorrect code was the following:

var bd:BitmapData = new BitmapData(w, h, true);

&#160;
The third boolean argument to the function is a transparency flag, and here it is set to true. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently ran into an issue where I thought I should have been drawing a transparent BitmapData object, but the resulting object had a white background. The original incorrect code was the following:</p>
<pre class="prettyprint">
var bd:BitmapData = new BitmapData(w, h, true);
</pre>
<p>&nbsp;<br />
The third boolean argument to the function is a transparency flag, and here it is set to true. However, when creating a Bitmap object from this BitmapData object and adding it to the display list, it clearly has a white background instead of being transparent.<br />
&nbsp;<br />
To remedy this, the solution is to pass along to the function a 32bit color value where the alpha value is zero. The following code illustrates this solution:</p>
<pre class="prettyprint">
var bd:BitmapData = new BitmapData(w, h, true, 0x00000000);
</pre>
<p>&nbsp;<br />
This will create a totally transparent BitmapData object on which you can draw whatever you desire. In practice I use this to determine the alpha values of a given pixel in a given display object. The following function implements this technique:</p>
<pre class="prettyprint">
public static function getAlphaAt(d:DisplayObject, x:Number, y:Number):Number {
	// Even though we set transparent to true, we still need to use a transparent color.
	// This is easily done by setting alpha to 0; the RGB octects after that don't matter.
	var bd:BitmapData = new BitmapData(d.width, d.height, true, 0x00000000);
	bd.draw(d);
	return (bd.getPixel32(x, y) >> 24 &#038; 0xFF)/255;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/01/12/flash-draw-transparent-bitmapdata/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flex Scale Image to Max Dimension</title>
		<link>http://www.bensnider.com/2010/01/11/flex-scale-image-to-max-dimension/</link>
		<comments>http://www.bensnider.com/2010/01/11/flex-scale-image-to-max-dimension/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 22:21:44 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[scaling]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=87</guid>
		<description><![CDATA[Recently had a problem where I needed to display images as large as possible within given bounds. So I made a handy little function that computes the scaling needed so that the image, if it is larger than any of the bounds, is scaled so that its largest dimension becomes equal to the given maximum. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently had a problem where I needed to display images as large as possible within given bounds. So I made a handy little function that computes the scaling needed so that the image, if it is larger than any of the bounds, is scaled so that its largest dimension becomes equal to the given maximum. This function scales the image proportionally so it won&#8217;t skew it.</p>
<pre class="prettyprint">
public function scaleImageToMaxDimension(img:Image, maxWidth:Number, maxHeight:Number):void {
	var scaleH:Number=1, scaleV:Number=1;
	if (img.content.height > maxHeight) {
		scaleV = maxHeight / img.content.height;
	}
	if (img.content.width > maxWidth) {
		scaleH = maxWidth / img.width;
	}
	img.scaleX = img.scaleY = Math.min(scaleH, scaleV);
}
</pre>
<p>&nbsp;<br />
Flex doesn&#8217;t do a terribly good job of resizing images, however, but it works for images that just need to be tweaked to fit. If you have control over your images and your display size, it is always best to resize them as needed to save space/bandwidth and preserve quality. This approach works best when you have little or no control over either.</p>
<p>In application this code would be used after the image has finished loading. So for example I might do something like the following:</p>
<pre class="prettyprint">
import flash.events.Event;
import mx.controls.Image;

public class Test {
	public var image:Image;

	// pretend scale function is here

	public function Test {
		image = new Image();
		image.addEventListener(Event.COMPLETE, imageComplete, false, 0, true);
		image.load('http://www.google.com/intl/en_ALL/images/logo.gif')
	}

	private function imageComplete(event:Event):void {
		scaleImageToMaxDimension(image, 100, 100);
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2010/01/11/flex-scale-image-to-max-dimension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>This Is Not a &#124;</title>
		<link>http://www.bensnider.com/2009/09/28/this-is-not-a/</link>
		<comments>http://www.bensnider.com/2009/09/28/this-is-not-a/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 18:09:34 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=82</guid>
		<description><![CDATA[
Saw this joke at this year&#8217;s Ohio Linux Fest during the closing talk, A Surfeit of Sophistication which was quite a good talk.
]]></description>
			<content:encoded><![CDATA[<p><img src="http://media.bensnider.com/images/this_is_not_a_linux.png" alt="This is not a |" /></p>
<p>Saw this joke at this year&#8217;s <a href="http://www.ohiolinux.org">Ohio Linux Fest</a> during the closing talk, <a href="http://www.ohiolinux.org/talks.html#SOPH">A Surfeit of Sophistication</a> which was quite a good talk.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2009/09/28/this-is-not-a/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flash 10 Valid Vector Elements</title>
		<link>http://www.bensnider.com/2009/08/19/flash-10-valid-vector-elements/</link>
		<comments>http://www.bensnider.com/2009/08/19/flash-10-valid-vector-elements/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 00:29:36 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=75</guid>
		<description><![CDATA[Finally got around to learning about the new collection class available in Flash 10. To be honest, I&#8217;m not terribly excited about many things in Flash 10, hence my slowness to adapt.
But, the vector class does interest me somewhat. It promises faster iteration over a strongly typed collection. Doesn&#8217;t seem to add any other handy [...]]]></description>
			<content:encoded><![CDATA[<p>Finally got around to learning about the new collection class available in Flash 10. To be honest, I&#8217;m not terribly excited about many things in Flash 10, hence my slowness to adapt.</p>
<p>But, the vector class does interest me somewhat. It promises faster iteration over a strongly typed collection. Doesn&#8217;t seem to add any other handy features however, like Flex&#8217;s robust ArrayCollection methods including removeItem. But alas. As for it being faster, I have heard talk around the internets of the vector class only being significantly faster with simple types, but I&#8217;m way too lazy to any informal benchmarks of my own, so I&#8217;ll just read someone else&#8217;s results.</p>
<p>One specific question I had that I didn&#8217;t see answered anywhere, however, was the type of objects you could stick in a vector once the template class had been set. It was my suspicion that you could put any subclass of the template class in the vector, just like C++ templated vetors, but I hadn&#8217;t read it confirmed anywhere, so I fired up my shiny new Flash CS4 and gave it a try. And indeed, my suspicion was correct. The following simple code below validates my hypothesis.</p>
<pre class="prettyprint">
var test:Vector.&lt;Sprite&gt; = new Vector.&lt;Sprite&gt;();
test.push(new Sprite(), new MovieClip());

// should output something like "[object Sprite],[object MovieClip]"
trace(test);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2009/08/19/flash-10-valid-vector-elements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Copying a Flash MovieClip, or The Flash Holy Grail</title>
		<link>http://www.bensnider.com/2009/05/15/copying-a-flash-movieclip-or-the-flash-holy-grail/</link>
		<comments>http://www.bensnider.com/2009/05/15/copying-a-flash-movieclip-or-the-flash-holy-grail/#comments</comments>
		<pubDate>Fri, 15 May 2009 23:41:31 +0000</pubDate>
		<dc:creator>BenSnider</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Front Page]]></category>

		<guid isPermaLink="false">http://www.bensnider.com/?p=65</guid>
		<description><![CDATA[Ran into a nice solution for copying arbitrary MovieClips at runtime today. I am designing a spot the difference game akin to 6 Differences with the requirement that, upon finding a difference, the scene should go to the &#8220;correct&#8221; state depending on which difference was defined as master, among a few other criterion. This required [...]]]></description>
			<content:encoded><![CDATA[<p>Ran into a nice solution for copying arbitrary MovieClips at runtime today. I am designing a spot the difference game akin to <a href="http://www.kongregate.com/games/Ivory/6-differences">6 Differences</a> with the requirement that, upon finding a difference, the scene should go to the &#8220;correct&#8221; state depending on which difference was defined as master, among a few other criterion. This required that I somehow duplicate, as much as is possible, the state of the &#8220;master&#8221; difference, when appropriate.</p>
<p>At any rate, the solution comes from <a href="http://www.dannyburbol.com/2009/01/movieclip-clone-flash-as3/">Danny Burbol&#8217;s blog</a>, which apparently came from a <a href="http://www.experts-exchange.com/Software/Photos_Graphics/Web_Graphics/Macromedia_Flash/Q_22684629.html">Experts Exchange thread</a> (damn people charging for information). I modified the solution a bit to fit my needs, but not by a whole lot. Sometimes I only need to copy the instance and I can reconstitute the MovieClip from there but other times I will need to get the whole shebang. It&#8217;s pretty handy in general. So my version follows (as a bonus I include my handy-dandy clearAllChildren function):</p>
<pre class="prettyprint">
package com.bmm.utils {
  import flash.display.DisplayObject;
  import flash.display.DisplayObjectContainer;
  import flash.geom.Rectangle;

  /**
   * ...
   * @author BenS
   */
  public class UIUtils {

    public static function clearAllChildren(c:DisplayObjectContainer):void {
      if (c == null || c.numChildren == 0) return;

      var i:int = 0, n:int = c.numChildren;
      for (i = 0; i < n; i++) {
        c.removeChildAt(0);
      }
    }

    public static function simpleDisplayObjectClone(source:DisplayObject):DisplayObject {
      var cc:Class = Object(source).constructor;
      return new cc();
    }

    public static function displayObjectClone(source:DisplayObject):DisplayObject {
      var copy:DisplayObject = UIUtils.simpleDisplayObjectClone(source);

      copy.transform = source.transform;
      copy.filters = source.filters;
      copy.cacheAsBitmap = source.cacheAsBitmap;
      copy.opaqueBackground = source.opaqueBackground;
      if (source.scale9Grid) {
        var r:Rectangle = source.scale9Grid;
        copy.scale9Grid = r;
      }

      return copy;
    }
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.bensnider.com/2009/05/15/copying-a-flash-movieclip-or-the-flash-holy-grail/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
