Skip to content

Instantly share code, notes, and snippets.

@mimshwright
Created November 26, 2009 02:38
Show Gist options
  • Save mimshwright/243196 to your computer and use it in GitHub Desktop.
Save mimshwright/243196 to your computer and use it in GitHub Desktop.
getOpaqueBounds() function added to InteractivePNG
/**
* Returns a rectangle around the opaque area of the png.
*
* @author Mims H. Wright
*/
public function getOpaqueBounds():Rectangle {
if (_bitmapForHitDetection==null)
drawBitmapHitArea();
var left:uint = 0;
var top:uint = 0;
var right:uint = width;
var bottom:uint = height;
// Start on the narrowest side because it will reduce the number of
// recursions on the longer side.
if (width > height) {
left = getLeft();
right = getRight();
top = getTop(left, right);
bottom = getBottom(left, right);
} else {
top = getTop();
bottom = getBottom();
left = getLeft(top, bottom);
right = getRight(top, bottom);
}
var opaqueBounds:Rectangle = new Rectangle();
opaqueBounds.left = left;
opaqueBounds.right = right - left;
opaqueBounds.top = top;
opaqueBounds.bottom = bottom - top;
return opaqueBounds;
function getLeft(startY:uint=0, endY:uint=0):uint {
// if endY isn't defined, use the height.
endY = endY == 0 ? height : endY;
var left:uint = 0;
var y:uint;
while (left < width) {
y = startY;
while (y < endY) {
if (isPixelOpaque(left, y)) return left;
y += 1;
}
left += 1;
}
// if there are no visible pixels, return the bounds.
return 0;
}
function getRight(startY:uint=0, endY:uint=0):uint {
// if endY isn't defined, use the height.
endY = endY == 0 ? height : endY;
var right:uint = width;
var y:uint;
while (right > 0) {
y = startY;
while (y < endY) {
if (isPixelOpaque(right, y)) return right;
y += 1;
}
right -= 1;
}
// if there are no visible pixels, return the bounds.
return width;
}
function getTop(startX:uint=0, endX:uint=0):uint {
// if endX isn't defined, use the width.
endX = endX == 0 ? width : endX;
var top:uint = 0;
var x:uint;
while (top < height) {
x = startX;
while (x < endX) {
if (isPixelOpaque(x, top)) return top;
x += 1;
}
top += 1;
}
// if there are no visible pixels, return the bounds.
return 0
}
function getBottom(startX:uint=0, endX:uint=0):uint {
// if endX isn't defined, use the width.
endX = endX == 0 ? width : endX;
var bottom:uint = height;
var x:uint;
while (x < endX) {
x = endX
while (x > startX) {
if (isPixelOpaque(x, bottom)) return bottom;
x -= 1;
}
bottom -= 1;
}
// if there are no visible pixels, return the bounds.
return height;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment