AS3 - 检查BitmapData是否被其他BitmapData完全遮挡

Ano*_*us1 1 actionscript-3 bitmapdata hittest

我想检查一个BitmapData对象是否完全被BitmapData对象遮挡.有什么像hitTest函数,但确保每个像素被覆盖而不是任何像素?

编辑:检查对象是否被遮挡时,不包括透明像素非常重要.

小智 5

毕竟它实际上是一个非常简单的解决方案!基本上你所做的只是捕获重叠位图占据的矩形区域中重叠位图的像素值.然后迭代这个值向量,只要你没有0(完全透明的像素),那么你就完全覆盖了下面的位图.

以下是我在此测试中使用的两个位图:

重叠位图:
在此输入图像描述

重叠的位图:
在此输入图像描述
码:

import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.utils.ByteArray;
import flash.geom.Rectangle;

var coveredBitmapData:BitmapData = new CoveredBitmapData();
var coveringBitmapData:BitmapData = new CoveringBitmapData();


var coveringBitmap:Bitmap = new Bitmap(coveringBitmapData, "auto", true);
var coveredBitmap:Bitmap = new Bitmap(coveredBitmapData, "auto", true);

coveredBitmap.x = Math.random() * (stage.stageWidth - coveredBitmap.width);
coveredBitmap.y = Math.random() * (stage.stageHeight - coveredBitmap.height);

stage.addChild(coveredBitmap);
stage.addChild(coveringBitmap);

stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMovement);

function onMouseMovement(e:MouseEvent):void
{
    coveringBitmap.x = mouseX - (coveringBitmap.width * .5);
    coveringBitmap.y = mouseY - (coveringBitmap.height * .5);

    checkIfCovering(coveringBitmap, coveredBitmap);
}

function checkIfCovering(bitmapA:Bitmap, bitmapB:Bitmap):Boolean
{
    //bitmapA is the covering bitmap, bitmapB is the bitmap being overlapped

    var overlappedBitmapOrigin:Point = new Point(bitmapB.x, bitmapB.y);

    var localOverlappedBitmapOrigin:Point = bitmapA.globalToLocal(overlappedBitmapOrigin);

    var overlappingPixels:Vector.<uint> = bitmapA.bitmapData.getVector(new Rectangle(localOverlappedBitmapOrigin.x, localOverlappedBitmapOrigin.y, bitmapB.width, bitmapB.height));

    if(overlappingPixels.length == 0) {
        //This means that there is no bitmap data in the rectangle we tried to capture. So we are not at all covering the underlying bitmap.
        return false;
    }

    var i:uint = 0;
    for(i; i < overlappingPixels.length; ++i) {
        if(overlappingPixels[i] == 0) {
            return false;
        }
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)