繁体   English   中英

Android 给 ImageView 添加边框图片

[英]Android add border image to ImageView

是否可以在Java中动态添加位图作为Android中ImageView的边框?

我已经尝试了以下方法:

XML中的图像视图和边框作为形状结果错误我想在边框中添加位图。

您有多种选择:

  1. 在 Imageview 上方放置一个带有边框(也是 imageview)的其他 View。 这可能是最简单的解决方案。 只需将其他视图添加到您的 xml 并确保它们重叠。 (例如使用相对或 FrameLayout 作为容器)

  2. 使用图层列表并在位图上方绘制一个形状并将其添加到您的 ImageView

  3. 写一个自定义的ImageView,在覆盖的onDraw方法中使用Canvas绘制Border。 例如 canvas.drawRect(...) 它非常简单。

简单的方法:

android:foreground ImageView属性的drawable

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">


    <stroke android:width="1px" android:color="#ff0000" />

    <solid android:color="@android:color/transparent"/>

</shape>

然后XML

<ImageView
    android:id="@+id/unreserved_head_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:foreground="@drawable/shape_border"
    />

我最近找到的最简单的解决方案。 尝试在您的应用中使用材料主题。 使用"Theme.MaterialComponents.Light"

然后使用里面的图像视图和材料卡视图。

        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardBackgroundColor="@color/white"
            app:cardCornerRadius="8dp"
            app:cardElevation="0dp"
            app:strokeColor="@color/colorPrimary"
            app:strokeWidth="1dp">
              
              <ImageView/>//define you image view hear
       
        </com.google.android.material.card.MaterialCardView>

使用属性stokeColorstrokeWidth您可以在图像视图上设置边框并使其动态化。

您可以在andorid studio中使用9个补丁来使图像成为边框!

我正在寻找解决方案,但没有找到,所以我跳过了那部分

然后我转到了firebase资产的谷歌图片,我偶然发现他们使用了9patch

9patch 在行动

继承人的链接: https : //developer.android.com/studio/write/draw9patch你只需要拖动边缘的位置

它就像统一的边界边缘

暂无
暂无

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

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