BlendMode Math

If you wonder, what blendmodes are doing exactly, you can read this article about blendmodes in common. I tried to work with them in a accurate way to emulate complexer algorithms like animated water waves. Generically you can save a lot of performance, if you need to calculate every single pixel colorvalue from two bitmaps. In most cases, there is a simple solution using ColorTransform and Blendmodes. One problem is that the flash results are different in some cases, so here are my findings:

// **BLENDMODES
// based on: http://www.pegtop.net/delphi/blendmodes/
// modified to fit flash output

/*
	[for each color component] RGB
*/

// ADD
// c' = Math.min( 255, Math.max( 0, c0 + c1 ) )

// SUBTRACT
// c' = Math.max( 0, c0 - c1 )

// MULTIPLY
// c' = Math.floor( ( c1 * c0 ) / 0xff )

// SCREEN
// c' = 255 - Math.floor( ( 255 - c0 ) * ( 255 - c1 ) / 255 )

// LIGHTEN
// c' = c0 > c1 ? c0 : c1

// DARKEN
// c' = c0 < c1 ? c0 : c1

// DIFFERENCE
// c' = c0 > c1 ? c0 - c1 : c1 - c0

// INVERT ( no influence from c1 )
// c' = 255 - c0

// OVERLAY
// c' = c0 < 128 ? Math.floor( ( c1 * c0 ) / 127 ) : 255 - Math.ceil( ( 255 - c0 ) * ( 255 - c1 ) / 127 )

// HARDLIGHT
// c' = c1 < 128 ? Math.floor( ( c1 * c0 ) / 127 ) : 255 - Math.ceil( ( 255 - c0 ) * ( 255 - c1 ) / 127 )

For example if you like to compute the average colors from 2 different bitmaps, you can follow like this:

import flash.display.*;
import flash.geom.*;

//-- test here 2 colorvalues
var c0: Number = 234;
var c1: Number = 255;

//-- source bitmaps
var b0: BitmapData = new BitmapData( 1, 1, false, c0 );
var b1: BitmapData = new BitmapData( 1, 1, false, c1 );

//-- resulting bitmap
var be: BitmapData = new BitmapData( 256, 256, false, 0 );

//-- compute average
var half: ColorTransform = new ColorTransform( .5, .5, .5, 1, 0, 0, 0, 0 );
be.draw( b0, new Matrix, half );
be.draw( b1, new Matrix, half, 'add' );

trace( be.getPixel( 0, 0 ) );
trace( Math.floor( ( c0 + c1 ) / 2 ) );

Of course this is a simple one, but you get the idea.

4 thoughts on “BlendMode Math”

  1. Hi Andre,

    want to ask you, if you have some nice example of animated water waves. This is what I always want to make in ActionScript. I have few solutions, but i’m not satisfied with them. So if you have something to show :) I would be glad :)

    Thanks

  2. Hi Andre,

    vielen Danke für deinen unkonventionellen Vortrag auf der MM Roadshow in Wien! Ich hab’s genossen einem Profi über die Schulter zu sehen. Eine Bitte: ist’s ev. möglich das coole Beispiel des Panoramas Sonnenuntergang ;) zu veröffentlichen? hiuer was so ziemlich alles drinnen, was es für Dummies wie mich zu lernen gibt…

    Reinhard

Comments are closed.