I'm trying to load a bitmap in Android which I want to tile. I'm currently using the following in my view to display a bitmap:
canvas.drawBitmap(bitmap, srcRect, destRect, null)
I essentially want to use this bitmap as a background image in my app and would like to repeat the bitmap in both the X and Y directions.
I've seen the TileMode.REPEAT constant for the BitmapShader
class but i am not sure if this is to be used for repeating the actual bitmap or is used for applying a filter to the bitmap.
You would do this in the xml instead of the java code. I haven't attempted this myself but I did find this example.
<xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/MainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/backrepeat"
>
then in an xml called backrepeat.xml
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/back"
android:tileMode="repeat" />
reference
Figured out the code version:
BitmapDrawable TileMe = new BitmapDrawable(MyBitmap);
TileMe.setTileModeX(Shader.TileMode.REPEAT);
TileMe.setTileModeY(Shader.TileMode.REPEAT);
ImageView Item = new ImageView(this);
Item.setBackgroundDrawable(TileMe);
Then if you have a drawable to tile, this can be used instead to make the BitmapDrawable:
BitmapDrawable TileMe = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.tile));
The backrepeat.xml above is buggy
<bitmap
xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/tile"
android:tileMode="repeat"
android:dither="true" />
It seems that some people are interested in doing this in a View, at the onDraw method. The following code has worked for me:
bgTile = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg_tile);
float left = 0, top = 0;
float bgTileWidth = bgTile.getWidth();
float bgTileHeight = bgTile.getHeight();
while (left < screenWidth) {
while (top < screenHeight) {
canvas.drawBitmap(bgTile, left, top, null);
top += bgTileHeight;
}
left += bgTileWidth;
top = 0;
}
<xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/MainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/back"
android:tileMode="repeat"
>
This worked fine for me. I did not have to create the bitmap seperately. I used the tileMode attribute in the layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With