android - 将背景图像设置为 View 会拉伸(stretch)我的 View

标签 android view background

我为 View 创建了背景图像位图,现在 View 被拉伸(stretch)到背景图像的大小......

这正常吗?

<?xml version="1.0" encoding="utf-8"?>
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/green"
        android:tileMode="repeat"/>

这是我如何将它应用到我的 View

v.setBackgroundResource(R.drawable.backgroundgreen);

比如……

如果图像高度为 500 像素 并且 View 高度为 200 像素(将 wrap_content 设置为高度) 将图像设置为背景后,我的 View 高度变为 500px...

最佳答案

我也遇到过同样的问题。

如果背景图像的大小大于 View 的大小,则 View 的大小将更改以匹配图像的大小。

解决方案


  1. 将 View 放在相对布局中。
  2. 移除背景图片。
  3. 在相对布局内的 View 之前添加一个 ImageView
  4. 将ImageView的src设置为你的背景图片

    <RelativeLayout
        .
        .
        . >
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/yourViewId"
            android:layout_alignRight="@+id/yourViewId"
            android:layout_alignTop="@+id/yourViewId"
            android:layout_alignBottom="@+id/yourViewId"
            android:adjustViewBounds="true" 
            //this will allow the image to resize with same proportions
            android:src="@drawable/yourDrawable" />
    
        <YourView
            android:id="@+id/yourViewId"
            .
            ..
            ... />
    
      </RelativeLayout>
    

当然,这一切都可以在代码中完成。

关于android - 将背景图像设置为 View 会拉伸(stretch)我的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202647/

相关文章:

android - 导出到 Gmail 时清空附件

Android 操作栏方向 RTL

php - 当相关表结构改变时mysql自动更新 View ?

python - Django Userena 更改 url 监护人错误

android - 如何通过许可或其他方式保护FCM服务

android - 如何从另一个子模块访问子模块的布局?

view - 如何查看智能手机等嵌入式设备的bootchart?

ios - iphone杀死后台应用程序

image - 去除视网膜的光盘图像,设置光盘的颜色为背景色

ios - WKWebView swiftUI 在第二次尝试时崩溃