2010-09-07 95 views
7

我想要使用只在水平平鋪的位圖,有沒有辦法做到這一點,以便它只會像CSS上的重複x一樣在X上展開。 我使用下面的代碼,但該位圖瓦片水平和垂直:Android上的位圖平鋪在X上只有

<?xml version="1.0" encoding="utf-8"?> 
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" 
    android:src="@drawable/pinstripe" 
    android:tileMode="repeat" 
    android:gravity ="top|fill_horizontal" 
    android:dither="true"/> 
+0

你有沒有想出一個解決方案嗎? – William 2011-01-11 18:53:16

回答

10

這裏是溶液。您可以在代碼中創建BitmapDrawable,並只指定X平鋪模式Android Tile Bitmap

+6

+1 Fedor:目前無法在XML中指定獨立的X和Y瓦片模式。 – Buzzy 2011-06-24 18:16:30

0

我想僅在垂直方向重複背景,但我找不到任何像樣的解決方案,所以我自己寫了這個,希望這可以幫助您有人在那裏*

/** 
* Created by LeoLink on 2014-06-24. 
*/ 
public class VerticallyRepeatedBackgroundLinearLayout extends LinearLayout { 
    private int width, height; 
    private RectF mRect; 

    public VerticallyRepeatedBackgroundLinearLayout(Context context) { 
     super(context); 
     init(context); 
    } 

    public VerticallyRepeatedBackgroundLinearLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     init(context); 
    } 

    public VerticallyRepeatedBackgroundLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     init(context); 
    } 

    private void init(Context context) { 
     setWillNotDraw(false); 
     mRect = new RectF(); 
    } 

    @Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) { 
     super.onSizeChanged(w, h, oldw, oldh); 
     if (oldw == 0 && oldh == 0 && w > 0 && h > 0) { 
      width = w; 
      height = h; 
     } 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     // clear the canvas 
     canvas.drawColor(Color.WHITE); 
     // draw 
     Drawable bg = getBackground(); 
     Bitmap bm = ((BitmapDrawable)bg).getBitmap(); 
     int w = bg.getIntrinsicWidth(); 
     int h = bg.getIntrinsicHeight(); 
     int drawWidth = width; 
     int drawHeight = drawWidth * h/w; 
     int bottom = 0; 
     while (height > bottom) { 
      mRect.set(0, bottom, drawWidth, bottom + drawHeight); 
      canvas.drawBitmap(bm, null, mRect, null); 
      bottom += drawHeight; 
     } 
    } 
} 

,並在你的XML

<com.blah.blah.VerticallyRepeatedBackgroundLinearLayout 
    android:id="@+id/collection_container" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/your_tile_bg"> 
</com.blah.blah.VerticallyRepeatedBackgroundLinearLayout>