Android学习Android开发Android知识

Android学习笔记043之shape详解

2016-08-18  本文已影响461人  张文文同学

Android中提供了shape形状给我们使用,我们可以通过shape画出虚线、圆角、渐变等多种效果,而且,shape是XML代码,比图片更小,在开发中,我们推荐使用shape,能用shape就用shape。

概述

用shape画形状,XML的根节点是shape,shape的取值有四个,简单的说就是,我们需要在根节点设置android:shape=""属性,这个属性取值有4个:rectangle(长方形),oval(椭圆),line(线条),ring(圆环)。

需要注意一下几个属性,只有在设置画的形状是ring(圆环)的时候才会起作用:

shape可以在Layout和selector中使用,shape有6个子标签,分别是:

需要注意的是:dashWidth和dashGap属性,只要其中一个设置为0dp或者不设置,边框是实线边框

使用

上面我们讲了很多shape的便签和属性,都是概念性的东西,下面我们来具体使用一下

使用shape画一条虚线

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="line">
<!-- 设置虚线的样式-->
<stroke
    android:width="2dp"
    android:color="@color/colorPrimaryDark"
    android:dashGap="5dp"
    android:dashWidth="8dp"/>

<size android:height="20dp"/>

</shape>

使用shape画一条实线

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="line">
<!-- 设置虚线的样式-->
<stroke
    android:width="2dp"
    android:color="@color/colorPrimaryDark"
    />

<size android:height="20dp"/>

</shape>

使用shape画一个实线边框

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

<stroke
    android:width="2dp"
    android:color="@color/colorPrimaryDark"/>
<corners android:radius="8dp"/>
</shape>

使用shape画一个虚线边框

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

<stroke
    android:width="2dp"
    android:color="@color/colorPrimaryDark"
    android:dashGap="3dp"
    android:dashWidth="5dp"/>

<corners android:radius="8dp"/>
</shape>

使用shape画一个渐变边框

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
<corners
    android:bottomLeftRadius="8dp"
    android:bottomRightRadius="8dp"
    android:topLeftRadius="8dp"
    android:topRightRadius="8dp"/>
<stroke
    android:width="2dp"
    android:color="@color/colorPrimaryDark"/>
<gradient
    android:angle="180"
    android:endColor="#197600"
    android:startColor="#9cff00"/>
</shape>

使用shape画一个圆环

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="ring"
   android:useLevel="false">
<solid android:color="#006BB0"/>
<stroke
    android:width="1dp"
    android:color="#ffffff"/>
<size
    android:width="20dp"
    android:height="20dp"/>
</shape>

最终实现的效果图是:

需要注意的是,在Android3.0之后会开启硬件加速功能,所以我们需要在Activity中添加

android:hardwareAccelerated="false"

这一句代码,否则不会显示虚线

shape就简单介绍到这里了,我们可以使用shape画出很多形状,就看具体的需求了,使用shape比图片更小。

上一篇 下一篇

猜你喜欢

热点阅读