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


当前回答

我差点就放弃了。

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

我的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"

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

其他回答

首先添加你想要的背景色作为你的边界的颜色,然后

更改cropToPadding为true,然后添加填充。

然后你就有了imageView的边框。

你必须在res/drawable这段代码中创建一个background.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="6dp" />
<stroke
    android:width="6dp"
    android:color="@android:color/white" />
<padding
    android:bottom="6dp"
    android:left="6dp"
    android:right="6dp"
    android:top="6dp" />
</shape>

我发现这样做容易得多:

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

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

在相同的xml中,我使用了下一个:

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffff" <!-- border color -->
        android:padding="3dp"> <!-- border width -->

        <ImageView
            android:layout_width="160dp"
            android:layout_height="120dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:scaleType="centerCrop" />
    </RelativeLayout>

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

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