如何在Android中为ImageView设置边框并更改其颜色?


当前回答

ImageView的xml文件

<ImageView
            android:id="@+id/myImage"
            android:layout_width="100dp"
            android:layout_height="100dp"

            android:padding="1dp"
            android:scaleType="centerCrop"
            android:cropToPadding="true"
            android:background="@drawable/border_image"

            android:src="@drawable/ic_launcher" />

以border_image.xml的名称保存下面的代码,它应该在可绘制文件夹中

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="270"
        android:endColor="#ffffff"
        android:startColor="#ffffff" />

    <corners android:radius="0dp" />

    <stroke
        android:width="0.7dp"
        android:color="#b4b4b4" />
</shape>

如果你想给图像的边界圆角,那么你可以改变border.xml文件中的一行

<corners android:radius="4dp" />

其他回答

以下是我曾经有黑色边框的代码。注意,我没有使用额外的xml文件为边界。

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/red_minus_icon"
    android:background="#000000"
    android:padding="1dp"/>

我发现这样做容易得多:

1)编辑帧内有内容(用9patch工具)。

2)将ImageView放置在线性布局中,并设置你想要的框架背景或颜色作为线性布局的背景。当你设置帧本身有内容时,你的ImageView将在帧内(就在你用9patch工具设置内容的地方)。

对于那些正在搜索自定义边界和形状的ImageView。你可以使用android-shape-imageview

只需添加compile 'com.github.siyamed:android-shape-imageview:0.9。+@aar'到build.gradle。

并使用在你的布局。

<com.github.siyamed.shapeimageview.BubbleImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/neo"
    app:siArrowPosition="right"
    app:siSquare="true"/>

我差点就放弃了。

这是我使用滑动加载图像的情况,请参阅关于圆角转换和这里的详细滑动问题

我的ImageView也有相同的属性,每个人都回答这里1,这里2,这里3

android:cropToPadding="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"`
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/path_to_rounded_drawable"

但还是没有成功。

经过一段时间的研究,使用前景属性从这个SO回答这里给出一个结果android:前景="@drawable/all_round_border_white"

不幸的是,它给我“不太好”的边界角如下图:

上面已经使用过,但没有专门提到。

setCropToPadding(boolean);

如果为真,图像将被裁剪以适合它的填充。

这将使ImageView源与背景填充相匹配。

通过XML它可以做到如下-

android:cropToPadding="true"