Thursday, March 31, 2011

Flipping BitmapData horizontally in Flash 9 or 10

Asking on behalf of my coworker:

We're working on a Facebook app that uses Flash 9 (and Flex, but that's not really relevant).

We've got a fairly complex system of drawing an object with accessories over it, where the accessories can have arbitrary scale, rotation, and position relative to the base object.

We recently started adding more features, including the ability to flip objects horizontally. For a similar but not identical part of the app, we can simply apply a negative horizontal scale in order to flip the object horizontally.

However, we're stuck when trying to draw the objects manually using the graphics api and graphics.beginBitmapFill(). According to some search results, we should be able to accomplish this by assigning a negative horizontal scale to the matrix passed into beginBitmapFill(), but this doesn't work.

Any ideas?

edit: Thanks guys. We'll be testing these and I'll let you know how it works out.

edit: I picked one! My coworker said, "The other one probably works too but just... no." :)

From stackoverflow
  • Here you go, this might not be 100% efficient but if you pass it a BitmapData object it will return to you the exact same one flipped horizontal.

    function flipBitmapDataHorizontal (b:BitmapData):BitmapData
    {
        var pixelList:Array = new Array();
        var pixelIndex:uint = 0;
    
        var i:uint;
        var j:uint;
    
        for(i = 0; i<b.height; i++){
         for(j = b.width; j>0; j--){
          var nextPixel:uint = b.getPixel32(j,i);
          pixelList.push(nextPixel);
          pixelIndex++;
         }
        }
    
        var newB:BitmapData = new BitmapData(b.width,b.height);
        var curPixel:uint = 0;
    
        for(i = 0; i<b.height; i++){
         for(j = 0; j<b.width; j++){
          newB.setPixel32(j,i,pixelList[curPixel++]);
         }
        }
    
        return newB;
    }
    
    jedierikb : Because you've made newB have the same width and height as b, this will crop your image (unless it happens to be a square).
    jedierikb : i am an idiot. i was rotating 90degrees, not flipping. :-)
  • How is your matrix constructed? You need to make sure as well as flipping the x scale that you also translate it back again across it's width. Here's an example with a MovieClip in the stage, where it is then drawn to a bitmap and flipped horizontally

    import flash.display.*;
    import flash.geom.*;
    
    var toFlip : MovieClip;
    
    var matrix : Matrix = new Matrix();
    matrix.scale(-1,1);
    matrix.translate(toFlip.width, 0);
    
    var bitmapData : BitmapData = new BitmapData(toFlip.width, toFlip.height, false, 0xFFFF0000);
    bitmapData.draw(toFlip, matrix);
    var bitmap : Bitmap = new Bitmap(bitmapData);
    
    addChild(bitmap);
    

0 comments:

Post a Comment