An ImageButton with border on mouseover

I thought I should share this with you. I was working on a project where I needed to set focus on an image which is a button. So I decided to create a border around it when it is moused over and remove it when the mouse is out.

Here is the code. I hope it helps someone. Note that it is developed in Actionscript, you can use any langauge once you get the simple logic.

/**
* This class draws a border around an image when the mouse roll over event occurs,
* and removes the border on a mouse roll out event
*
* Developed By Oluwaseun Ladeinde.
*/
package mycustoms
{
import flash.events.Event;
import flash.events.MouseEvent;

import mx.controls.Image;

//add sytyle meta tags to the class. This enables a control of these properties from the css file
[Style(name=”borderColor”, type=”uint”, format=”Color”, inherit=”no”)]
[Style(name=”borderThickness”, type=”Number”, format=”Length”, inherit=”no”)]
[Style(name=”borderAlpha”, type=”Number”, format=”Length”, inherit=”no”)]

public class BorderedImage extends Image
{
public function BorderedImage()
{
super();

//add event listeners to the roll over and roll out events
this.addEventListener(MouseEvent.MOUSE_OVER, drawBorder);
this.addEventListener(MouseEvent.MOUSE_OUT, clearBorder);
}

// Handler the mouse roll over event
private function drawBorder(event:Event):void
{
// get the border artifacts and set to false
graphics.lineStyle(getStyle(‘borderThickness’), getStyle(‘borderColor’), getStyle(‘borderAlpha’),false);

// then redraw the border
graphics.drawRect( -(getStyle(‘borderThickness’)/2), -(getStyle(‘borderThickness’)/2),
contentWidth+getStyle(‘borderThickness’), contentHeight+getStyle(‘borderThickness’));
}

// Handler the mouse roll out event
public function clearBorder(event:Event):void
{
//simply clear the graphics
graphics.clear();
}

public function enable(_enabled:Boolean):void
{
if(_enabled == false)
{
this.enabled = _enabled;
this.buttonMode = _enabled;
this.useHandCursor = _enabled;
this.removeEventListener(MouseEvent.MOUSE_OVER, drawBorder);
}
else
{
this.enabled = _enabled;
this.buttonMode = _enabled;
this.useHandCursor = _enabled;
this.addEventListener(MouseEvent.MOUSE_OVER, drawBorder);
}
}
}
}

*********************************

I hope it helps you somewhere in your flex project.

Advertisements