android - 在 x 中制作位图可绘制平铺但在 y 中拉伸(stretch)

标签 android android-view

我有一张图像用作 RelativeLayout 的背景。图像需要水平平铺以形成图案。

我可以使用以下代码使图像水平平铺:

BitmapDrawable b3 = (BitmapDrawable)getResources().getDrawable(R.drawable.background);

b3.setTileModeX(Shader.TileMode.REPEAT);

v.findViewById(R.id.layout).setBackgroundDrawable(b3);

问题是图像也垂直平铺。它似乎在垂直方向以“夹紧”模式平铺,但在水平方向以“重复”模式平铺。这是一个屏幕截图:

TileMode

如您所见,图像比它占据的空间小一点点,底部边缘被“夹紧”。

如何设置图像垂直拉伸(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/

相关文章:

android - EditText - 以编程方式更改文本选择背景颜色

android - ConstraintLayout TextView

java - 如何将 Libgdx 游戏部署到 iOS

android - OnTouchListerner 不应将打开 DrawerLayout 的滑动解释为长按

Android - 在 invalidate() 上重绘后的监听器

java - 在 Android 中设置视频作为背景播放

android - 如何将可绘制文件夹中的图像放入 HTML 文件

android - 定义的方法永远不会被调用

Android wifi 设备发现和消息传递

android - "getDataDir()"与 getFilesDir 有何不同?