2010-10-22 122 views
3

因此,我設法讓自己停留在需要在舞臺上放置充滿圖像(各種產品的透明圖像)的數據庫的情況,所有這些都需要對齊產品高度相同。修剪透明PNG周圍的空白

我的問題是,PNG的產品是'浮動',我無法控制它將坐在PNG的哪裏(可能是在頂部和底部的空間負載,反之亦然)

有沒有人知道現有的方法來找出PNG的'真正'的高度(寬度是一個額外的)。我想過關於循環位圖數據並檢查,但想知道是否有人已經發明瞭這個輪子?

例如Example with room at top/Example with none, really

+0

有趣的問題 - 我想循環的兩個方向是你最好的選擇 – danjp 2010-10-22 16:27:04

+0

是啊,我只是相信,我不能成爲第一個需要雙向透明度檢查器的人。但是,如果沒有,我會繼續併發揮。 – karlfreeman 2010-10-22 16:35:56

回答

1

我最終得出的解決方案是下面的,很可能不是最高效的方式,但它的工作原理。

/** 
    * Cuts off the transparency around a bitmap, returning the true width and height whilst retaining transparency 
    * 
    * @param input Bitmap 
    * 
    */ 
    private function trimTransparency(input:BitmapData,colourChecker:uint = 0x00FF00):Bitmap { 

     //Keep a copy of the original 
     var orignal:Bitmap = new Bitmap(input); 

     //Clone the orignal with a white background 
     var clone:BitmapData = new BitmapData(orignal.width, orignal.height,true,colourChecker); 
     clone.draw(orignal); 

     //Grab the bounds of the clone checking against white 
     var bounds:Rectangle = clone.getColorBoundsRect(colourChecker, colourChecker, false); 

     //Create a new bitmap to return the changed bitmap 
     var returnedBitmap:Bitmap = new Bitmap(); 
     returnedBitmap.bitmapData = new BitmapData(bounds.width, bounds.height,true,0x00000000); 
     returnedBitmap.bitmapData.copyPixels(orignal.bitmapData,bounds, new Point(0,0));  
     return returnedBitmap; 


    } 
3

正如阿利斯泰爾說,該getColorBoundsRect最終將是您最佳的選擇。

我還沒有看太多,但我不確定getColorBoundsRect是否允許您「選擇所有非100%alpha-ed像素」。如果沒有,您可以輕鬆使用BitmapData.threshold方法使您進入該階段。

我會做類似於複製位圖的東西,在其上運行閾值方法將所有非alpha-ed像素變成鮮綠色,然後運行getColorBoundsRect選擇您剛剛創建的所有綠色像素。

+0

感謝Trevor,發佈了我的解決方案,它遵循與您的相同的主題,但沒有超出門檻。原來你可以替換背景,然後在負空格上運行getColorBoundsRect。 – karlfreeman 2010-10-26 09:31:25

+1

我會避免使用白色作爲你的背景填充......如果你有一個白色的邊框圖像會發生什麼? – 2010-10-26 12:13:49

+0

真正的白色邊框會把這種大風格搞砸。嗯,我會進一步看看它,也許有旁邊的輸入另一個顏色填充默認爲綠色。好一個。 – karlfreeman 2010-10-26 13:08:31

1

這是我想出了一個解決方案,如果有人需要:

public static function trimAlpha(source:BitmapData):BitmapData { 
     var notAlphaBounds:Rectangle = source.getColorBoundsRect(0xFF000000, 0x00000000, false); 
     var trimed:BitmapData = new BitmapData(notAlphaBounds.width, notAlphaBounds.height, true, 0x00000000); 
     trimed.copyPixels(source, notAlphaBounds, new Point()); 
     return trimed; 
    }