Android: drawing tiled bitmaps with bottom or some other alignments similar to css background-position

I want to set the View background with a tiled bitmap, but the tile should be snapped to the lower left and not to the upper left corner (default). For example, if the tiles are emoticons below, I want them to be broken as:

enter image description here

Using xml drawables, I could do either shingles (using tileMode="repeat") or bottom positioning (using gravity="bottom"), but combining both is not possible, even the documentation says so:

Android: TILEMODE

Keyword. Defines the tile mode. When tile mode is on, the bitmap is repeated. Gravity is ignored when tile mode is on.

, , , ?

+2
3

BitmapDrawable paint():

, .

class MyBitmapDrawable extends BitmapDrawable {
    private Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
    private boolean mRebuildShader = true;
    private Matrix mMatrix = new Matrix();

    @Override
    public void draw(Canvas canvas) {
        Bitmap bitmap = getBitmap();
        if (bitmap == null) {
            return;
        }

        if (mRebuildShader) {
            mPaint.setShader(new BitmapShader(bitmap, TileMode.REPEAT, TileMode.REPEAT));
            mRebuildShader = false;
        }

        // Translate down by the remainder
        mMatrix.setTranslate(0, getBounds().bottom % getIntrinsicHeight());
        canvas.save();
        canvas.setMatrix(mMatrix);
        canvas.drawRect(getBounds(), mPaint);
        canvas.restore();
    }
}

:

view.setBackgroundDrawable(new MyBitmapDrawable(getResources().getDrawable(R.drawable.smiley).getBitmap()));
+5

, , , , , ?

+1

Using a custom view may include processing all the drawing yourself, and not just the background image.

Instead, I suggest setting the focus of the view programmatically, as shown:

// This drawable refers to an image directly and NOT an XML
BitmapDrawable smiley = (BitmapDrawable) getResources().getDrawable(R.drawable.smiley);

// Create a new bitmap with the size of the view
Bitmap bgBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bgBitmap);

// Translate down by the remainder
Matrix matrix = new Matrix();
matrix.setTranslate(0, view.getHeight() % smiley.getIntrinsicHeight());
canvas.setMatrix(matrix);

// Tile the smileys
Paint paint = new Paint();
paint.setShader(new BitmapShader(smiley.getBitmap(), TileMode.REPEAT, TileMode.REPEAT));
canvas.drawPaint(paint);

view.setBackgroundDrawable(new BitmapDrawable(bgBitmap));

Questions to consider:

  • I am not sure that view.getWidth () and view.getHeight () are correct methods for getting dimensions.
  • What if the emoticon size is larger than the view?
+1
source

All Articles