how*_*ttl 7 android android-view
我有一个图像,我用它作为RelativeLayout的背景.图像需要水平平铺以制作图案.
我可以使用以下代码将图像水平平铺:
BitmapDrawable b3 = (BitmapDrawable)getResources().getDrawable(R.drawable.background);
b3.setTileModeX(Shader.TileMode.REPEAT);
v.findViewById(R.id.layout).setBackgroundDrawable(b3);
Run Code Online (Sandbox Code Playgroud)
问题是图像也垂直拼贴.它似乎在垂直方向处于"钳位"模式,而在水平方向处于"重复"模式.这是一个截图:
如您所见,图像比它占据的空间略小,底边被"夹紧".
如何将图像设置为垂直拉伸但水平平铺?
此方法调用新位图的创建,但看起来它正在实现您的目标
View view = findViewById(R.id.layout);
BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.tile);
int width = view.getWidth();
int intrinsicHeight = bd.getIntrinsicHeight();
Rect bounds = new Rect(0,0,width,intrinsicHeight);
bd.setTileModeX(TileMode.REPEAT);
bd.setBounds(bounds);
Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), bd.getBitmap().getConfig());
Canvas canvas = new Canvas(bitmap);
bd.draw(canvas);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), bitmap);
view.setBackground(bitmapDrawable);
Run Code Online (Sandbox Code Playgroud)
请注意,它仅在视图已经布局时才有效,因此方法lile onWindowFocusChanged
是此代码的好地方.