我有一张图像用作 RelativeLayout 的背景。图像需要水平平铺以形成图案。
我可以使用以下代码使图像水平平铺:
BitmapDrawable b3 = (BitmapDrawable)getResources().getDrawable(R.drawable.background);
b3.setTileModeX(Shader.TileMode.REPEAT);
v.findViewById(R.id.layout).setBackgroundDrawable(b3);
问题是图像也垂直平铺。它似乎在垂直方向以“夹紧”模式平铺,但在水平方向以“重复”模式平铺。这是一个屏幕截图:
如您所见,图像比它占据的空间小一点点,底部边缘被“夹紧”。
如何设置图像垂直拉伸(stretch)但水平平铺?
最佳答案
此方法调用了新位图的创建,但看起来它正在实现您的目标
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);
请注意,它仅在 View 已经布局时才有效,因此 onWindowFocusChanged
方法是放置此代码的好地方。
关于android - 在 x 中制作位图可绘制平铺但在 y 中拉伸(stretch),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7450415/