android shape 属性详解

我们在做android UI开发时,经常会使用到各种各样的背景,很多情况下都是直接设置图片作为背景,背景图片过大,则会很影响内存,在这里我们可以使用shape来绘制一些实用的背景。shape是形状、模型的意思,首先来看一个效果图:

这里写图片描述

怎样用shape来实现这种多效果的背景呢,先附上相关代码,然后进行解释。

1、创建一个shape文件,命名为bg_shape_view.xml,将其保存在drawable文件夹中。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#ba45b9" />
    <corners
        android:bottomLeftRadius="20dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="20dp"
        android:topRightRadius="10dp" />
    <padding
        android:bottom="4dp"
        android:left="4dp"
        android:right="4dp"
        android:top="4dp" />
    <gradient
        android:angle="45"
        android:centerColor="#b22bb5"
        android:endColor="#f6ce11"
        android:startColor="#21b057"
        android:type="linear" />
    <size
        android:width="200dp"
        android:height="100dp" />
    <stroke
        android:width="3dp"
        android:color="#0638d4"
        android:dashGap="8dp"
        android:dashWidth="10dp" />
</shape>

2、我们来创建一个布局文件,activity_shape.xml,将TextView的背景设置成bg_shape_view后,运行即可实现上面的运行效果。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:background="@drawable/bg_shape_view"
        android:gravity="center"
        android:text="This is a test for shape" />
</RelativeLayout>

3、shape属性介绍

3.1 solid属性
颜色填充,可选属性有android:color=”#ba45b9”,指填充的颜色值。

3.2 corners属性
圆角,可选属性有android:radius=”8dp”,指定矩形四个圆角的度数都是8dp。
也可以分别设置每个圆角的度数,如下分别进行设置:

android:bottomLeftRadius="20dp" //表示左下角的度数;
android:bottomRightRadius="10dp" //表示右下角的度数;
android:topLeftRadius="20dp" //表示左上角的度数;
android:topRightRadius="10dp" //表示右上角的度数。

3.3 padding属性
作用同View的padding属性。

3.4 gradient属性
渐变效果,可设置多种渐变的效果,可选值[linear],[radial],[sweep]:

android:type="linear" //指线性渐变
android:angle="45" //此属性配合linear使用,值为45的倍数,表示从顺时针开始,哪个角度开始进行渐变

android:type="radial" //径向渐变
android:gradientRadius="60dp" //此属性配合radial使用。

android:type="sweep" //扫描效果

android:centerColor="#b22bb5" //设置中间颜色值
android:endColor="#f6ce11" //设置起始颜色值
android:startColor="#21b057" //设置末尾颜色值

3.5 size属性
设置区域的宽和高。

android:width="200dp"
android:height="100dp" 

3.6 stroke属性
区域描边,设置区域的边框。

android:width="3dp"  //边框的宽度大小
android:color="#0638d4" //边框的颜色
android:dashGap="8dp" //边框的可选属性,设置之后,边框会变成虚线的样式,此属性设置虚线的间隔
android:dashWidth="10dp" //设置虚线的长度

只需要合理配合以上各属性,你就可以绘制出各种炫酷的背景效果图。

发布了27 篇原创文章 · 获赞 32 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/luoyingxing/article/details/51580247
今日推荐