There are several ways you can attack this. I will talk about two of them here ...
One of the methods:
You can define a BitmapDrawable around a bitmap. Set TileMode to repeat. Give it some restrictions via setBounds (rect), where rect is your Rect instance.
The following is a brief example of using the onDraw view context as:
public class MyView extends View { Rect rect; Bitmap mBitmap; BitmapDrawable mDrawable; public MyView(Context context) { super(context); rect = new Rect(0, 0, 100, 100); mBitmap = loadBitmap(); mDrawable = new BitmapDrawable(context.getResources(), mBitmap); mDrawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT); mDrawable.setBounds(rect); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mDrawable.draw(canvas); } public Bitmap loadBitmap() {
Note:
You can also define BitmapDrawable in xml instead of doing it in code.
Also, if you know what you are loading with getResources (), getDrawable (resourceId) is just a bitmap, you can drop it into BitmapDrawable and set TileMode there. A la:
public class MyView extends View { Rect rect; BitmapDrawable mDrawable; public MyView(Context context) { super(context); rect = new Rect(0, 0, 400, 240); mDrawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher); mDrawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT); mDrawable.setBounds(rect); this.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.ic_launcher)); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mDrawable.draw(canvas); } }
This example shows a stretched background and a tiled version drawn on top of it.
Another way:
Loop in the x and y direction and re-draw the bitmap in the rectangle:
public class MyView extends View { Rect rect; Bitmap mBitmap; public MyView(Context context) { super(context); rect = new Rect(0, 0, 100, 100); mBitmap = loadBitmap(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); final int bmWidth = mBitmap.getWidth(); final int bmHeight = mBitmap.getHeight(); for (int y = 0, height = rect.height(); y < height; y += bmHeight) { for (int x = 0, width = rect.width(); x < width; x += bmWidth) { canvas.drawBitmap(mBitmap, x, y, null); } } } public Bitmap loadBitmap() {
I personally would go for the first (BitmapDrawable) method.