Created
January 29, 2014 23:01
-
-
Save azrafe7/8699079 to your computer and use it in GitHub Desktop.
Simple applyAlphaMask for haxe/openfl...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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: 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.
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
Wouldn't copyChannel do the same job?
targetBitmap.copyChannel(sourceBitmap, sourceBitmap.rect, new Point(), BitmapDataChannel.ALPHA, BitmapDataChannel.ALPHA);