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


当前回答

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

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

其他回答

创建边界

创建一个xml文件(例如:"frame_image_view.xml")和以下内容在你的可绘制文件夹:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="@dimen/borderThickness"
        android:color="@color/borderColor" />
    <padding
        android:bottom="@dimen/borderThickness"
        android:left="@dimen/borderThickness"
        android:right="@dimen/borderThickness"
        android:top="@dimen/borderThickness" />
    <corners android:radius="1dp" /> <!-- remove line to get sharp corners -->
</shape>

替换@dimen/borderThickness和@color/borderColor与任何你想要或添加相应的dimen/ color。

添加Drawable作为ImageView的背景:

<ImageView
        android:id="@+id/my_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/frame_image_view"
        android:cropToPadding="true"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter" />

你必须使用android:cropToPadding="true",否则所定义的填充没有效果。或者在ImageView中使用android:padding="@dimen/borderThickness"来实现相同的效果。 如果边框帧父视图而不是ImageView,尝试使用android:adjustViewBounds="true"。

改变边框颜色

在代码中更改边框颜色的最简单方法是使用tintbackground属性。

ImageView img = findViewById(R.id.my_image_view);
img.setBackgroundTintList(ColorStateList.valueOf(Color.RED); // changes border color to red

or

ImageView img = findViewById(R.id.my_image_view);
img.setBackgroundTintList(getColorStateList(R.color.newColor));

不要忘记定义你的newColor。

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

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

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

然后你就有了imageView的边框。