Установите форму в качестве фона ImageView, чтобы скруглить верхние углы

Я пытаюсь создать макет с помощью ConstraintLayout с закругленными углами внутри ScrollView. В верхней части макета я хочу разместить изображение, верхние углы которого должны быть закруглены (чтобы соответствовать углам макета), а нижние углы прямые.

Следуя предложениям, которые я нашел в этом вопросе StackOverflow, вот мой код:

<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/scroll_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_weight="7.5"
        android:background="@color/darkModePrimary">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:layout_width="match_parent"
            android:background="@drawable/layout_bg"
            android:layout_height="wrap_content">

            <ImageView
                android:background="@drawable/layout_bg"
                android:src="@drawable/house_medium"
                android:id="@+id/house_image"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="fitXY"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"/>

            <TextView
                android:layout_marginTop="32dp"
                android:gravity="center"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@id/house_image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Some text"
                android:textSize="24sp"/>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Это файл xml, в котором я определяю форму фона ConstraintLayout.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white"/>
    <corners android:radius="10dp"/>
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
</shape>

Если я установлю эту фигуру в качестве фона как для Constraint Layout, так и для ImageView, я получу, как и ожидалось, изображение со всеми четырьмя закругленными углами, как показано здесь.

изображение с четырьмя прямыми углами

Я попытался создать другую форму для использования в качестве фона изображения, например:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white"/>
    <corners android:bottomRightRadius="0dp"
        android:bottomLeftRadius="0dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp"/>
</shape>

Но когда я устанавливаю его в качестве фона ImageView, я не получаю то, что хочу, все четыре угла изображения теперь прямые.

изображение с четырьмя прямыми углами

Что я делаю неправильно?


person Mike    schedule 09.08.2020    source источник
comment
Просто поместите макет карты в CardView и измените app:cardCornerRadius.   -  person dmtr    schedule 09.08.2020
comment
По ряду причин я решил не использовать CardViews, а создать макет самостоятельно, поэтому, к сожалению, я не могу этого сделать.   -  person Mike    schedule 09.08.2020
comment
хорошо, тогда попробуйте добавить атрибут размера. ‹размер android:width=100dp android:height=100dp/›   -  person dmtr    schedule 09.08.2020


Ответы (1)


Чтобы заставить его работать, просто установите в коде схему размещения контейнера вашей карты.

  • В макете xml добавьте идентификатор в контейнер карты:

      <androidx.constraintlayout.widget.ConstraintLayout
          android:id="@+id/card"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginLeft="16dp"
          android:layout_marginTop="16dp"
          android:layout_marginRight="16dp"
          android:background="@drawable/layout_bg"
          android:elevation="4dp">
    
  • В вашей MainActivity onCreate:

    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
    
         card.clipToOutline = true
         card.outlineProvider = ViewOutlineProvider.BACKGROUND
    }
    

Результат: введите здесь описание изображения

person dmtr    schedule 09.08.2020