Long time ago I needed to create a text message where the font was filled with icons.
The idea was quite simple, find a point over the text, and then expand a rectangle checking that the four corners are still overlapping the text.
Now I decide that is time to use bitmaps, and blendModes, to allow not only rectangles, but any other shape over our text, and this is the result.
The proccess in this case is the next:
- Find a point over our source.
- Draw over that point our element, with the minimal size allowed.
- Grow the element, while all pixels intersect the source.
This in resume, and translate to code, looks like this:
// Find a point over the source using the hitTest function _sourceBitmap.hitTest(ZERO_POINT, 0, new Point(xo,yo)) // Over a copy of the source, draw bitmap our object, with blend mode set to erase // setting the parameters of the matrix to rotate and scale our object _colisionBitmap = _sourceBitmap.clone(); _colisionBitmap.draw(DisplayObject(fill) ,matrix ,null, 'erase') // Apply a threshold to check the number of pixels we have after the subtraction pixels = _colisionBitmap.threshold(_colisionBitmap, _colisionBitmap.rect , new Point() , '>', 0x00000000, 0xffffffff, 0xffffffff); // If the number of pixels of our object is the same as the pixels removed, // we know all the object is over our source. hit = objectPixels = substractedPixels; // If we had a hit, we can scale up the object and do loop again // getting at the end the biggest overlapping object for the selected point. // We also need to add a time check to leave the loop in case no match is found. if (loopTime>_timeLimit) break;
To run the algorithm we just need the next lines:
// create a test area for our source (displayElement) overlapArea = new OverlapArea(source); // set the minimal, maximal and variation scale, for the object to draw over the source overlapArea.setScale( 0.1 , 1.0 , 0.05 ); // get an overlapping object for our object var overlapData:Object = overlapArea.getOverlapArea(obj);
This algorithm, will return null (if no match is found) or an object with the position, scale, and rotation of our object.
With this data, we know where we can place a MovieClip, Sprite or any other element to our screen, that overlap our source, making things like load images or adding user interaction, very simple.