Flex tutorial: Setting tile image as background

This tutorial shows you how to fill a Canvas background with repeated images. We will make use of the BitmapData.draw() function to achieve this. Note that if the image to be repeated is from another domain (i.e. a cross domain image), you have to ensure that the domain has a cross domain policy file, and you have to set checkPolicyFile=true in order to get it working. Otherwise, you will get a security sandbox error. More explanation here.

Demo:
Tile Image Background (view source enabled)

Source Codes: main application


<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	xmlns:mx="http://www.adobe.com/2006/mxml"
	xmlns:alekkus="com.alekkus.*"
	layout="absolute"
	backgroundColor="#F8F8F8">

<mx:Script>
  <![CDATA[
  	import mx.controls.Image;

	private function onClick() : void
	{
		// 1. for crossdomain images, we need to create a LoaderContext object and set its checkPolicyFile to true.
		var loaderContext : LoaderContext = new LoaderContext ();
		loaderContext.checkPolicyFile = true;

		// 2. assign that loaderContext object to an Image object
		var image : Image =  new Image();
		image.loaderContext =  loaderContext;

		// 3. set source and load
		image.source = "http://alekkus.com/flex3/extra/images/duck.jpg"
		image.addEventListener( Event.COMPLETE, onImageLoaded  );
		image.load();
	}

	private function onImageLoaded( event : Event ) : void
	{
		var image : Image = Image( event.currentTarget );

		// 1. set as tile image background
		cvsMain.setTileImage( image );
	}

  ]]>
</mx:Script>

	<alekkus:TileImageCanvas id="cvsMain" width="100%" height="100%" />
	<mx:Button x="10" y="10" label="Set background as tile image" click="onClick()" />

</mx:Application>

Source Codes: TileImageCanvas class


<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas
	xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Script>
<![CDATA[
	import mx.controls.Image;

	private var _image : Image = null;

	public function setTileImage( image : Image ) : void
	{
		this._image = image;
		this.invalidateDisplayList();
	}

    override protected function updateDisplayList( unscaledWidth : Number, unscaledHeight : Number ) : void
    {
        super.updateDisplayList(unscaledWidth, unscaledHeight );

        if ( _image != null )
        {
	        var bitmap : Bitmap = Bitmap( _image.content );
	        var bitmapData : BitmapData = new BitmapData( bitmap.width, bitmap.height );
	        bitmapData.draw( bitmap );      

	        graphics.clear();
	        graphics.beginBitmapFill( bitmapData );
	        graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
	        graphics.endFill();
	    }
    }
]]>
</mx:Script>
</mx:Canvas>

  This blog is powered by WordPress with GimpStyle Theme design by Horacio Bella.