Flex canvas provide a style attribute backgroundImage which allow us to set an image as background. Compare with the background in Html5 and CSS, this feature is not that user friendly. In CSS, we can not only set the background image, but also tell the css how to render the background image if the image is not big enough to cover the whole display object like DIV. This is a so basic feature while the Flex canvas style doesn’t support it. If we want to get this feature done, we have to write the code by ourself. First, let’s see what the background image effect I am talking about.

Repeat Background Image
Flex Repeat Background Image Example

In the above example, I just want to set background image to 300×150 canvas. In flex, we can set a 300×150 image to canvas style attribute backgroundImage. But this is not the efficient way. If there is a 3000×1500 canvas, will we need to prepare 3000×1500 image for it? In the HTML CSS traditional way, we can simply set the css attribute like:

body
{
    background-image:url('gradient2.png');
    background-repeat:repeat-x;
}

Flex don’t support this basic feature by default. There are some alternative ways to make it come true, but I don’t think they are good enough. There is one swc library which implement the CSS style mechanism in Flex. It allows you to assign the background image in the css way. In Flex 4 example, we can also define skin class to support the repeat background image. But if you see the source code, you will decide to keep away from it. In that way, we need to write hundred lines of code to repeat the background image. Actually, it is not that complicated to implement. In my example, I just write 10 lines.

			protected function generateBg(event:FlexEvent):void
			{
				var headerBitmap:BitmapAsset = BitmapAsset(new bgClass());
				this.styledContainer.graphics.beginBitmapFill(headerBitmap.bitmapData, null, true, true);
				this.styledContainer.graphics.drawRect(0, 0, this.styledContainer.width, this.styledContainer.height);
			}

First, we embed the background image in our application and use BitmapAsset to get the background image bitmapdata which we want to apply to the canvas background. Then we can use graphics to draw and fill the image inside the canvas. Here is the final effect:

Download Canvas Repeat Background Image Example Source Code

Previous PostNext Post

Leave a Reply

Your email address will not be published. Required fields are marked *