ImageView超出父Android Studio XML

时间:2019-06-28 17:53:33

标签: android xml android-layout imageview android-imageview

我如何让孩子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>

enter image description here

我有一个实现自定义视图的片段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不会裁剪到具有自定义背景的父视图的边界。请注意,左角未圆化

enter image description here

CardListAdapter

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

3 个答案:

答案 0 :(得分:1)

因此,您的问题中存在一些误解。我要解决的第一件事是您的假设:

  

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

您的子视图实际上尊重父视图的范围。圆角不是父View的边界,而是View内可绘制对象的裁剪。您称为自定义视图的custom_view.xml文件实际上是一个自定义可绘制对象,它被用作父对象的背景。它对ConstraintLayout的边界没有影响。

如果您希望图像也具有圆角,我鼓励您找到有关裁剪ImageView的源的教程。使用Google搜索可以找到一些简单的教程,其中包括Romain Guy的一个教程,以及Medium上的几个教程,可以为您解决问题。

回顾一下:您的子视图实际上是在尊重父级的边界,您应用于该视图的背景实际上并不是父级的边界,只有一个可绘制对象充当该父级边界内的背景父视图。因此,您将需要对图像执行某种类型的蒙版或剪切或构建自定义ImageView类来自动剪切其内容。

答案 1 :(得分:0)

ImageView实际上满足您设置的约束。那是因为父母的界限不会改变。 这是一个解决方案:将ImageView的边距与match_parent的width和height结合使用,以使其适合圆形的父对象,并在侧面留一点边框。玩边距尺寸(以dp为单位),直到找到所需的内容。

答案 2 :(得分:0)

您可以创建另一个left_corner.xml并将其应用于子ImageView,请尝试以下操作:

    <shape android:shape="rectangle">
      <corners android:backgroundTint="@color/backgroundColor" android:bottomLeftRadius="10dp" android:topLeftRadius="10dp" android:bottomRightRadius="0dp" android:topRightRadius="0dp" />
      <solid android:color="@color/backgroundBlue" />
    </shape>

希望有帮助。