简体   繁体   English

在不调整容器大小的情况下通过重力设置背景在Android中查看

[英]Set background with gravity without resizing the container View in Android

How can I add a background to a view, without resizing its size, only showing the part of the image that fits the previous space? 如何在不调整大小的情况下向视图添加背景,而仅显示适合上一空间的图像部分?

Example: 例:

I have the following initial layout: 我有以下初始布局:

在此处输入图片说明

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#8900"
    android:orientation="vertical"
    tools:context="com.tappx.myapplication.MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:background="#0f0"
            android:gravity="center"
            android:text="HELLO" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:background="#f0f"
            android:gravity="center"
            android:text="HELLO" />


    </LinearLayout>


</LinearLayout>

And I want to apply the following image as gradient to the white background: 我想将以下图像作为渐变应用于白色背景:

在此处输入图片说明

To achieve this (please note the gradient is filling the horizontal and has bottom gravity): 为此(请注意,渐变填充水平并且具有底部重力):

TARGET: 目标: 在此处输入图片说明

My problem is that setting the gradient as android:background expands the container view size to this (losing the red bottom part) 我的问题是将渐变设置为android:background会将容器视图大小扩展为此(丢失红色底部)

在此处输入图片说明

Also tried making a xml bitmap with no results: 还尝试制作没有结果的xml位图:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <bitmap
            android:gravity="bottom"
            android:src="@drawable/gradient" />
    </item>
</layer-list>

How can I achieve it? 我该如何实现?

The image you are using is very long, and your container is set to wrap content and so it is expanding to accommodate the image. 您使用的图像很长,并且您的容器设置为包装内容,因此正在扩展以容纳该图像。

Since you are already using fixed heights on the inner elements, you can simply set a fixed height for the container (200dp) and it'll work 由于您已经在内部元素上使用了固定的高度,因此您只需为容器设置固定的高度(200dp),它就会起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM