zoukankan      html  css  js  c++  java
  • 解决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方式设置背景,均不会产生被拉伸的情况。

    本文转自:http://blog.csdn.net/oathevil/article/details/23707359

  • 相关阅读:
    科幻的意义---《超新星纪元》后记
    论文翻译第二弹--用python(或Markdown)对论文复制文本进行处理
    python note 001
    matlab读取txt文本
    VS中添加lib与dll
    Wake-Sleep(W-S)算法【转载】
    清华大学《C++语言程序设计进阶》线上课程笔记06---继承、派生、多态性
    清华大学《C++语言程序设计基础》线上课程笔记05---vector对象,对象的复制与移动,string类
    清华大学《C++语言程序设计基础》线上课程笔记04---指针
    Linux线程的信号量同步
  • 原文地址:https://www.cnblogs.com/sishuiliuyun/p/3729820.html
Copyright © 2011-2022 走看看