Drawing diagonals lines for a background pattern in Flex with SpriteVisualElement

An example of square/rectangle filled with diagonal lines. You can adjust the corner radius, spacing between diagonal lines, the line color and the background color. The class extends spark.core.SpriteVisualElement, so it can be dropped in to Spark containers and be laid out and rendered correctly. I used it as a textured background to a play card skin where is easily mixed up with other FXG graphics.

The example is straightforward so I am not going into many details here. It’s worth mentioning though the usage of caching for drawing and data commands, so they are recalculated only when needed. To be more specific, a change in the width or height, will need to be reflected in the diagonal lines being redrawn on the screen. Same goes for spacing. However a change in the cornerRadius by itself will only determine the redrawing of the mask. To make this happen, when changing the values for the properties in question one invalidates the parent by calling invalidateParentSizeAndDisplayList(). This in turn will trigger a call to setLayoutBoundsSize() from the parent’s side.

/**
 * @private
 * @param value Number
 */
public function set spacing(value:Number):void
{
	if (_spacing == value)
	{
		return;
	}

	if (value < 3) 	{ 		value = 3; 	} 	if (value > 100)
	{
		value = 100;
	}

	_invalidateCache = true;
	_spacing = value;
	invalidateParentSizeAndDisplayList();
}

Inside the overridden setLayoutBoundsSize() we can hook the drawing code to redraw the changes:

override public function setLayoutBoundsSize(width:Number, height:Number, postLayoutTransform:Boolean = true):void
{
	super.setLayoutBoundsSize(width, height, postLayoutTransform);
	drawPattern();
}

protected function drawPattern():void
{
	if (_invalidateCache)
	{
		_invalidateCache = false;
		validateCache();
	}

	drawBackground();
	drawDiagonals()

	if (_maskDirty)
	{
		_maskDirty = false;
		drawMask();
	}
}

Props to Andy Hulskamp for this example, which I used as a starting point. As usual sourcecode is available for download.

Leave a Reply

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

*