2010-10-22 120 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; 
    }