【问题标题】:Maintain aspect ratio with LinearLayout.setBackgroundResource()使用 LinearLayout.setBackgroundResource() 保持纵横比
【发布时间】:2015-10-31 18:05:32
【问题描述】:

我正在使用myLinearLayout.setBackgroundResource(R.drawable.my_drawable) 设置LinearLayout 的背景。使用此方法而不是让图像拉伸以适应LinearLayout 时,有什么方法可以保持源图像的纵横比(必要时缩放以适应)?

xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/background_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    ...

</LinearLayout>

java 文件:

backgroundLayout.setBackgroundResource(R.drawable.my_drawable);

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    当我必须设置布局的背景时(让我们将其命名为 Layout_A),我使用 RelativeLayout 作为父级,并在其中放置 2 个项目:

    • 缩放类型设置为 centercrop 的 ImageView
    • 布局_A

    xml 将是:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@drawable/background"/>
    
        <Layout_A>
    
            ...
    
        </Layout_A>
    
    </RelativeLayout>
    

    您需要更改背景的代码是:

    ImageView ivBackground = (ImageView) rootView.findViewById(R.id.background);
    ivBackground.setImageDrawable(getResources().getDrawable(R.drawable.my_drawable));
    

    或:

    ImageView ivBackground = (ImageView) rootView.findViewById(R.id.background);
    ivBackground.setImageResource(R.drawable.my_drawable);
    

    【讨论】:

    • 我使用了这个答案,但使用FrameLayout 而不是RelativeLayout 作为根元素:*.com/q/22875453/1438339。在实践中可能没有区别,我想两者都应该没问题。