将 imageview 内的图像约束到 android:background 形状

Posted

技术标签:

【中文标题】将 imageview 内的图像约束到 android:background 形状【英文标题】:constraint image inside imageview to android:background shape 【发布时间】:2022-01-14 23:07:55 【问题描述】:

在我的回收视图中,我显示了一个图像/图标列表。这些是导航到下一个活动的透明徽标。我拥有的一些图像超出了圆圈的轮廓。 我想为显示的图标添加一个最大高度/最大宽度以消除这种行为。有时图标不受椭圆形约束,而是方形圆形父布局(约束) 有什么方法可以限制 xml 中的 src 图像?这是雷诺标志的外观:

我的代码:

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/root_view"
    android:layout_
    android:layout_>

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/main_image"
        android:layout_
        android:layout_
        android:adjustViewBounds="false"
        android:background="@drawable/circle_background"
        android:scaleType="fitCenter"
        app:layout_constraintDimensionRatio="1.0"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

还有我的选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="@color/black"/>
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/blue" />
        </shape>
    </item>
</selector>

上面的空 ImageView。我更改了背景颜色以说明约束问题。我不想填充空白。

【问题讨论】:

第一张图片是你想要的还是你想要避免的?换句话说,雷诺原木当前是否延伸到圆圈之外,这是您不想要的,或者,圆圈是否应该夹住徽标,使其具有圆形顶部,如第一个视图所示。也许您希望整个徽标都放在圆圈内? 我希望整个徽标适合圆圈内。问题是我收到了许多尺寸不同的它们等,即使我将它们居中,它们也有些不合适。但它们匹配正方形(父)的约束 在 ImageView 上应用适当的顶部和底部填充将使图像在圆形背景中居中。但是,每个图像的填充可能不同。根据徽标,您可能会遇到左右两侧不合适的问题。左/右填充将解决这些问题。如果不根据具体情况进行一些计算,则没有任何限制来拟合圆。 【参考方案1】:

请尝试以下比例类型

android:scaleType="fitXY"

【讨论】:

以上是关于将 imageview 内的图像约束到 android:background 形状的主要内容,如果未能解决你的问题,请参考以下文章

带有自动布局的滚动视图内的iOS 8 imageView不起作用

从 Parse (Swift) 中检索图像到 imageView

如何限制将捏缩放图像移动到图像边框?

滚动视图内的约束

如何使 ImageView 出现在圆圈内的随机位置?

将 View 定位在 ImageView 内的 Drawable 之上