• android:background背景图片被拉伸问题


    ImageView中XML属性src和background的区别:

    background会根据ImageView组件给定的长宽进行拉伸,而src就存放的是原图的大小,不会进行拉伸。src是图片内容(前景),bg是背景,可以同时使用。

    此外:scaleType只对src起作用;bg可设置透明度,比如在ImageButton中就可以用android:scaleType控制图片的缩放方式


    如上所述,background设置的图片会跟View组件给定的长宽比例进行拉伸。举个例子, 36x36 px的图标放在 xhdpi 文件夹中,在854x480(FWVGA,对应hdpi)环境下,按照

    xhdpi : hdpi : mdpi: ldip = 2 : 1.5 : 1 : 0.75

    的比例计算,在FWVGA下,图标的实际大小应该是 27x27。

    但是当我把它放到一个 layout_width = 96px, layout_height = 75px 的 LinearLayout,布局代码如下:

        <LinearLayout android:gravity="center" android:layout_width="96px" android:layout_height="75px"  >  
            <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/toolbar_bg"/>      
        </LinearLayout>  

    实际情况是,我们得到的ImageButton的大小是 33x27,很明显width被拉伸了,这是我们不想看到的情况。

    解决方案一:

    代码中动态显式设置ImageButton的layout_width和layout_width,如下

        LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(27, 27);  
        layout.addView(imageButton, layoutParam);  

    不过,事实上我们并不希望在代码存在“硬编码”的情况。

     

    解决方案二:

    在你通过setBackgroundResource()或者在xml设置android:background属性时,将你的background以XML Bitmap的形式定义,如下:

     <?xml version="1.0" encoding="utf-8"?>  
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"  
        android:id="@id/toolbar_bg_bmp"  
        android:src="@drawable/toolbar_bg"  
        android:tileMode="disabled" android:gravity="top" >  
    </bitmap> 

    调用如下:

     

        imageButton.setBackgroundResource(R.drawable.toolbar_bg_bmp)

    或者

        <ImageButton ...  android:background="@drawable/toolbar_bg_bmp" ... />

    若背景图片有多种状态,还可参照toolbar_bg_selector.xml:

        <?xml version="1.0" encoding="utf-8"?>  
        <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
            <item android:state_pressed="true" >  
                <bitmap android:src="@drawable/toolbar_bg_sel" android:tileMode="disabled" android:gravity="top" />  
            </item>  
            <item >  
                <bitmap android:src="@drawable/toolbar_bg" android:tileMode="disabled" android:gravity="top" />  
            </item>  
        </selector>  

    如此,不管是通过代码方式setBackgroundResource()或XML android:background方式设置背景,均不会产生被拉伸的情况。

  • 相关阅读:
    人工智能 tensorflow框架-->简介及安装01
    【亲测】自动构建多个指定的class并发执行:Jenkins+Maven+Testng框架
    【亲测】Appium测试Android混合应用时,第二次切换到WebView失败
    appium_v1.4.16版本自动化适配android7.0系统
    python之拆包与装包
    python3之线程
    python3之进程
    python3之tcp
    python3之udp
    python3面向对象(4)之__new__方法和__init__方法
  • 原文地址:https://www.cnblogs.com/xiaoli3007/p/4322822.html
Copyright © 2020-2023  润新知