2014-10-30 60 views
0

我有一個場景,我需要設置一個位圖作爲gridLayout的背景。 我用下面的代碼:圖像延伸設置爲GridLayout的背景

Drawable drawable = new BitmapDrawable(context.getResources(), bitmap); 
bgView.setBackgroundDrawable(drawable); 

哪裏bgView是GridLayout的位圖是我從遠程服務器接收的位圖。

上面設置圖像作爲背景,但它延伸。 我需要圖像在背景中居中。 任何人都可以幫助我排序這個問題如何居中背景圖像。

回答

0

一些以前,我有同樣的情況。
我通過把ImageView作爲背景解決了這個問題。
它看起來像這樣:

grid_item.xml

<FrameLayout> 

    <!-- wrap original with FrameLayout then put ImageView as bg! --> 
    <ImageView /> 

    <OriginalLayout> 
    ... 
    <OriginalLayout> 

</FrameLayout> 

如果OriginalLayoutFrameLayoutRelativeLayout或類似的東西,
你不必與FrameLayout

希望它提示你包解決。

0

您必須創建另一個位圖,可以在不拉伸的情況下填充網格佈局。就我個人而言,我更喜歡填充完整的背景,將其填充到畫布中(通過縮放),然後進一步裁剪(也稱爲中心裁剪)。我發現這個代碼:

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) { 
    int sourceWidth = source.getWidth(); 
    int sourceHeight = source.getHeight(); 

    // Compute the scaling factors to fit the new height and width, respectively. 
    // To cover the final image, the final scaling will be the bigger 
    // of these two. 
    float xScale = (float) newWidth/sourceWidth; 
    float yScale = (float) newHeight/sourceHeight; 
    float scale = Math.max(xScale, yScale); 

    // Now get the size of the source bitmap when scaled 
    float scaledWidth = scale * sourceWidth; 
    float scaledHeight = scale * sourceHeight; 

    // Let's find out the upper left coordinates if the scaled bitmap 
    // should be centered in the new size give by the parameters 
    float left = (newWidth - scaledWidth)/2; 
    float top = (newHeight - scaledHeight)/2; 

    // The target rectangle for the new, scaled version of the source bitmap will now 
    // be 
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight); 

    // Finally, we create a new bitmap of the specified size and draw our new, 
    // scaled bitmap onto it. 
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig()); 
    Canvas canvas = new Canvas(dest); 
    canvas.drawBitmap(source, null, targetRect, null); 

    return dest; 
} 

用法:從遠程服務器(IST參數)的位圖,寬度和網格佈局(IIND和IIIrd參數)和使用高度返回的位圖作爲您的網格佈局的背景。

希望它會有所幫助。 (PS:它不會增加你的視圖層次結構另一個解決方案是將imageview放在你的網格後面並設置其縮放類型centerCrop並在其中設置背景圖像)。