2

我想使用平铺位图设置视图的背景,但平铺需要锚定到左下角,而不是左上角(默认)。例如,如果瓷砖是下面的笑脸,我希望它像这样平铺:

在此处输入图像描述

使用 xml drawables 我可以实现平铺(使用tileMode="repeat")或底部定位(使用gravity="bottom"),但是将两者结合起来是不可能的,即使文档是这样说的:

安卓:平铺模式

关键词。定义平铺模式。启用平铺模式时,重复位图。启用平铺模式时忽略重力。

虽然它不受内部支持,但有没有办法实现这一点,也许使用自定义视图?

4

3 回答 3

5

另一种方法是扩展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()));
于 2012-03-22T02:01:28.060 回答
1

只是一个想法,它非常迂回,但是你能垂直翻转你的图像,然后对你的背景应用一个变换来垂直翻转吗?

于 2012-03-21T08:41:58.330 回答
1

使用自定义视图可能涉及自己处理所有绘图,而不仅仅是背景图像。

相反,我建议以编程方式设置视图的背景,如下所示:

// 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));

需要考虑的要点:

  • 我不确定 view.getWidth() 和 view.getHeight() 是否是获取尺寸的正确方法。
  • 如果笑脸尺寸大于视图怎么办?
于 2012-03-21T23:59:41.393 回答