Showing posts with label Datagrid. Show all posts
Showing posts with label Datagrid. Show all posts

Saturday, June 5, 2010

Datagrid with Random Cell Colors

Flex has rich component sets having a lot of properties and styles to use according to our requirement. Even if we don't get our requirement, we can easily extend a component and add our stuffs to get the result. When It comes to give each cell a random background color or different background color I have extended a Datagrid component and overridden the protected function drawRowBackground().

By default flex Datagrid draws each row with same color from alternatingItemColors. We can use ItemRenderer to fulfil our job, however I think this is an easier trick.
  • Custom component extended from Datagrid
  • overrides the drawRowBackground() function to add random color.
               override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, 
 height:Number, color:uint, dataIndex:int):void
{
// used the DisplayObject instead of ListBaseContentHolder because that is excluded
var disObj:DisplayObject = s.parent;
var background:Shape;
var redBias:Number = 0xFF;
var greenBias:Number = 0xFF;
var blueBias:Number = 0xFF;
if (rowIndex < s.numChildren)
{
background = Shape(s.getChildAt(rowIndex));
}
else
{
background = new FlexShape();
background.name = "background";
s.addChild(background);
}
background.y = y;
// Height is usually as tall is the items in the row, but not if
// it would extend below the bottom of listContent
var height:Number = Math.min(height,
disObj.height -
y);
var g:Graphics = background.graphics;
var xCoord:Number = 0;
var numColumns:int = this.columns.length; // number of columns
g.clear();
/* this will loop for no of columns and generate a random color
* x Coordinate increases as column no increases*/
for (var i:int=0; i < (numColumns); i++)
{
var ct:ColorTransform = new ColorTransform(1, 1, 1, 1, 
Math.random() * redBias, Math.random() * greenBias, Math.random() * blueBias);
g.beginFill(ct.color, getStyle("backgroundAlpha"));
g.drawRect(xCoord, 0, unscaledWidth, height);
xCoord += DataGridColumn(this.columns[i]).width;
g.endFill();
}






Now as the basic things done we can modify it according to our requirement.