问题描述
我想设置一个铺位图视图的一个背景,但平铺需要,而不是左上角(默认)被固定在左下角。例如,如果瓷砖低于笑脸,我希望它平铺,如:
I want to set a background of a View with a tiled bitmap, but the tiling needs to be anchored to the bottom-left, instead of the top-left corner (the default). For example, if the tiles are the smiley faces below, I want it to be tiled like:
使用XML绘图资源,我可以做到无论是贴砖(使用 TILEMODE =重复
)或底部位置(使用比重=底
),但两者结合起来是不可能的,即使文档是这么说的:
Using xml drawables I could achieve either tiling (using tileMode="repeat"
) or bottom positioning (using gravity="bottom"
), but combining both is not possible, even the documentation says so:
安卓TILEMODE
关键词。定义平铺模式。当平铺模式
启用,该位图被重复。的重力被忽略的时候平铺模式
已启用。
Keyword. Defines the tile mode. When the tile mode is enabled, the bitmap is repeated. Gravity is ignored when the tile mode is enabled.
虽然它的内部不支持,有没有办法实现这个目标,可能使用自定义视图?
Although it's not internally supported, is there any way to achieve this, perhaps using custom views?
推荐答案
另一种方法是延长 BitmapDrawable
并重写的paint()
方法:
Another way would be to extend BitmapDrawable
and override the paint()
method:
的在这个方法中,我们的避免创建具有视图的大小新位图。的
In this method we avoid creating a new bitmap having the size of the view.
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();
}
}
它可以设置为这样的观点:
It can be set to the view like this:
view.setBackgroundDrawable(new MyBitmapDrawable(getResources().getDrawable(R.drawable.smiley).getBitmap()));
这篇关于安卓:绘制与底部或一些其他路线类似于CSS背景位置的瓷砖位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!