0
点赞
收藏
分享

微信扫一扫

Android shape画带边框矩形

Android shape画带边框矩形

在Android开发中,我们经常需要使用矩形背景,以及带有边框的矩形。Android提供了ShapeDrawable来实现这一功能。在本文中,我们将学习如何使用ShapeDrawable绘制带有边框的矩形,并给出相应的代码示例。

ShapeDrawable简介

ShapeDrawable是一个可绘制的图形对象,它可以用来绘制各种形状,如矩形、圆形、椭圆等。在这里,我们将使用ShapeDrawable来绘制矩形。

绘制带边框的矩形

要绘制带有边框的矩形,我们需要使用ShapeDrawable的setShape(Shape shape)方法来设置矩形形状,并使用setStroke(int width, int color)方法来设置边框的宽度和颜色。

下面是一个绘制带边框的矩形的代码示例:

// 创建ShapeDrawable对象
ShapeDrawable shapeDrawable = new ShapeDrawable();

// 创建矩形形状对象
RectShape rectShape = new RectShape();

// 设置矩形形状
shapeDrawable.setShape(rectShape);

// 设置边框宽度和颜色
shapeDrawable.setStroke(2, Color.BLACK);

在布局中使用带边框的矩形

在布局中使用带边框的矩形非常简单。我们可以使用<shape>标签来定义矩形形状,并使用<solid><stroke>标签来设置填充色和边框。

下面是一个使用带边框的矩形作为背景的布局的代码示例:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/rectangle_with_border"
    android:padding="16dp">

    <!-- 布局的其他内容 -->

</LinearLayout>

res/drawable目录下,我们创建一个名为rectangle_with_border.xml的文件,并在其中定义矩形形状和边框:

<shape xmlns:android="
    <solid android:color="#FFFFFF" /> <!-- 填充色 -->
    <stroke
        android:width="2dp" <!-- 边框宽度 -->
        android:color="#000000" /> <!-- 边框颜色 -->
    <corners android:radius="8dp" /> <!-- 圆角半径 -->
</shape>

总结

本文介绍了如何使用ShapeDrawable绘制带有边框的矩形,并且给出了相应的代码示例。通过使用ShapeDrawable,我们可以轻松地实现各种形状的背景和边框效果,为我们的Android应用增添一些视觉上的吸引力。

以上就是关于Android shape画带边框矩形的介绍。希望本文对你有所帮助!

举报

相关推荐

0 条评论