首页 > 解决方案 > ImageView 超过父 android studio xml

问题描述

如何将子ImageView剪辑制作到其父母的边界?当我将 ImageView 作为子项添加到具有圆角的父视图时,子 ImageView 不符合圆角。

我努力了:
android:cropToPadding
android:clipChildren
android:clipToPadding
android:adjustViewBounds

我已在图像视图和父视图以及所有可能的组合上将这些设置为 true 和 false。

我有一个自定义视图:custom_view.xml圆角

<shape android:shape="rectangle">
  <corners android:backgroundTint="@color/backgroundColor" android:radius="10dp" />
  <solid android:color="@color/backgroundBlue" />
</shape>

在此处输入图像描述

我有一个片段,fragment_card.xml它实现了自定义视图。

<android.support.constraint.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:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="105dp"
    android:layout_margin="10dp"
    android:background="@drawable/custom_view"   <-- setting the custom_view
    app:cardBackgroundColor="@color/colorAccent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <ImageView
        android:id="@+id/cardIconView"
        android:layout_width="105dp"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/line_separator"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
and it continues...

子 ImageView 不会剪辑到具有自定义背景的父视图的边界。注意左角不是圆角

在此处输入图像描述

CardListAdapter

override fun onBindViewHolder(holder: CardViewHolder, position: Int) { 
  holder.cardIconView.setImageDrawable(theimage)
}

标签: androidxmlandroid-layoutimageviewandroid-imageview

解决方案


因此,您的问题在这里发生了一些误解。我要解决的第一件事是您的假设:

“当我将 ImageView 作为子项添加到具有圆角的父视图时,子 ImageView 不符合圆角。”

您的子视图实际上是在尊重父视图的边界。圆角不是父级的边界View,而是View. 您所说的自定义视图,custom_view.xml文件,实际上是一个自定义可绘制对象,用作父级的背景。它对边界没有影响ConstraintLayout

如果你希望你的图像也有圆角,我鼓励你找到一个关于剪辑ImageView. 谷歌搜索可以找到几个简单的教程,包括来自 Romain Guy 的一个,以及一些在 Medium 上的教程,它们可以为你解决问题。

回顾一下:您的子视图实际上尊重父视图的边界,您应用到视图的背景实际上并不是父视图的边界,只是作为父视图边界内的背景的可绘制对象。因此,您将需要对图像执行某种类型的遮罩或剪辑,或者构建一个自定义ImageView类来自动剪辑其内容。


推荐阅读