Android中是使用shape分别绘制四个边的边框
时间: 2024-03-05 12:54:49 浏览: 79
在 Android 中,可以使用 shape 资源来分别绘制四个边的边框。以下是使用 shape 绘制四个边的边框的步骤:
1. 创建一个 shape 资源文件,例如 border_shape.xml。在该文件中,使用 shape 标签定义形状和风格。为了分别绘制四个边的边框,可以使用 inset 标签来定义边框的位置和大小,例如:
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent" />
<inset
android:insetLeft="1dp"
android:insetTop="1dp">
<shape>
<stroke
android:width="1dp"
android:color="#FF0000" />
</shape>
</inset>
<inset
android:insetTop="1dp"
android:insetRight="1dp">
<shape>
<stroke
android:width="1dp"
android:color="#FF0000" />
</shape>
</inset>
<inset
android:insetRight="1dp"
android:insetBottom="1dp">
<shape>
<stroke
android:width="1dp"
android:color="#FF0000" />
</shape>
</inset>
<inset
android:insetBottom="1dp"
android:insetLeft="1dp">
<shape>
<stroke
android:width="1dp"
android:color="#FF0000" />
</shape>
</inset>
</shape>
```
上述代码定义了一个矩形形状,四个边的边框宽度为 1dp,颜色为红色。使用 inset 标签来定义边框的位置和大小,例如 insetLeft 定义了左边框的宽度为 1dp,insetTop 定义了上边框的宽度为 1dp。
2. 在布局文件中,将对应的 View 的背景设置为该 shape 资源即可,例如:
```
<View
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border_shape" />
```
这样,该 View 就会显示出一个四边分别绘制边框的矩形形状。可以根据需要调整 shape 资源中的属性来修改边框的风格和形状。
注意:如果要在代码中动态设置边框,可以使用 setBackground 方法来设置 View 的背景。例如:
```
view.setBackground(ContextCompat.getDrawable(context, R.drawable.border_shape));
```
阅读全文
相关推荐



















