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


当前回答

我发现这样做容易得多:

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

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

其他回答

下面是我对这个漫长麻烦的最简单的解决方案。

<FrameLayout
    android:layout_width="112dp"
    android:layout_height="112dp"
    android:layout_marginLeft="16dp" <!-- May vary according to your needs -->
    android:layout_marginRight="16dp" <!-- May vary according to your needs -->
    android:layout_centerVertical="true">
    <!-- following imageView acts as the boarder which sitting in the background of our main container ImageView -->
    <ImageView
        android:layout_width="112dp"
        android:layout_height="112dp"
        android:background="#000"/>
    <!-- following imageView holds the image as the container to our image -->
    <!-- layout_margin defines the width of our boarder, here it's 1dp -->
    <ImageView
        android:layout_width="110dp"
        android:layout_height="110dp"
        android:layout_margin="1dp"
        android:id="@+id/itemImageThumbnailImgVw"
        android:src="@drawable/banana"
        android:background="#FFF"/> </FrameLayout>

在下面的答案中,我已经解释得很好了,请大家也看看!

我希望这将有助于其他人在那里!

在相同的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>

对于那些正在搜索自定义边界和形状的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"/>

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

setCropToPadding(boolean);

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

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

通过XML它可以做到如下-

android:cropToPadding="true"

你必须在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>