Skip to content

Instantly share code, notes, and snippets.

@azrafe7
Created January 29, 2014 23:01
Show Gist options
  • Save azrafe7/8699079 to your computer and use it in GitHub Desktop.
Save azrafe7/8699079 to your computer and use it in GitHub Desktop.
Simple applyAlphaMask for haxe/openfl...
/**
* Masks the `source` BitmapData (in place) using alpha data from `alphaMask`.
*
* Note: `source` and `alphaMask` must be of the same size.
*
* @param source BitmapData to be masked.
* @param alphaMask BitmapData to be used as mask.
* @param copyAlpha If true the alpha value of `alphaMask` will be copied over to `source`.
*/
public static function applyAlphaMask(source:BitmapData, alphaMask:BitmapData, copyAlpha:Bool = false):Void
{
var sourceRect = source.rect;
var sourceBytes:ByteArray = source.getPixels(sourceRect);
var alphaMaskBytes:ByteArray = alphaMask.getPixels(sourceRect);
sourceBytes.position = 0;
alphaMaskBytes.position = 0;
var nPixels:Int = Std.int(sourceRect.width * sourceRect.height);
var sourceAlpha:Int = 0;
var maskAlpha:Int = 0;
var alphaIdx:Int = 0;
for (idx in 0...nPixels) {
alphaIdx = idx << 2;
maskAlpha = alphaMaskBytes[alphaIdx];
sourceAlpha = sourceBytes[alphaIdx];
sourceBytes[alphaIdx] = copyAlpha ? maskAlpha : sourceAlpha * (maskAlpha > 0 ? 1 : 0);
}
source.setPixels(sourceRect, sourceBytes);
}
@musanek
Copy link

musanek commented Feb 8, 2014

Wouldn't copyChannel do the same job?

targetBitmap.copyChannel(sourceBitmap, sourceBitmap.rect, new Point(), BitmapDataChannel.ALPHA, BitmapDataChannel.ALPHA);

@azrafe7
Copy link
Author

azrafe7 commented Feb 11, 2014

@musanek: Yes, this behaves like copyChannel if you set copyAlpha = true, but I needed to replicate the behaviour of copyPixels with alphaBitmapData (which is done with this snippet and copyAlpha = false).

Basically if the mask has alpha > 0 outside opaque pixels of the source don't copy it over.

@dmouton
Copy link

dmouton commented Dec 19, 2014

Is there a way to have something faster than that ?
for (idx in 0...nPixels) {
alphaIdx = idx << 2;
maskAlpha = alphaMaskBytes[alphaIdx];
sourceAlpha = sourceBytes[alphaIdx];
sourceBytes[alphaIdx] = copyAlpha ? maskAlpha : sourceAlpha * (maskAlpha > 0 ? 1 : 0);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment