Android样式开发之shape

来源:互联网 发布:漫画算法 编辑:程序博客网 时间:2024/06/05 20:38

AndroidStudio中如何创建shape的XML文件

在drawable(一般用shape定义的xml文件存放在drawable目录下)中new一个Drawable resource file,添加File name,Root element填写shape即可。

使用shape可以定义下面四种类型的形状,通过android:shape属性指定

  • rectangle: 矩形,默认的形状,可以画出直角矩形、圆角矩形、弧形等
  • oval: 椭圆形,用得比较多的是画正圆
  • line: 线形,可以画实线和虚线
  • ring: 环形,可以画环形进度条

shape的子标签以及标签里的属性

  • solid: 设置形状填充的颜色,只有android:color一个属性
    • android:color填充的颜色
  • padding: 设置内容与形状边界的内间距,可分别设置左右上下的距离
    • android:left左内间距
    • android:right右内间距
    • android:top上内间距
    • android:bottom下内间距
  • gradient: 设置形状的渐变颜色,可以是线性渐变、辐射渐变、扫描性渐变
    • android:type渐变的类型
      • linear线性渐变,默认的渐变类型
      • radial放射渐变,设置该项时,android:gradientRadius也必须设置
      • sweep扫描性渐变
    • android:startColor渐变开始的颜色
    • android:endColor渐变结束的颜色
    • android:centerColor渐变中间的颜色
    • android:angle渐变的角度,线性渐变时才有效,必须是45的倍数,0表示从左到右,90表示从下到上
    • android:centerX渐变中心的相对X坐标,放射渐变时才有效,在0.0到1.0之间,默认为0.5,表示在正中间
    • android:centerY渐变中心的相对X坐标,放射渐变时才有效,在0.0到1.0之间,默认为0.5,表示在正中间
    • android:gradientRadius渐变的半径,只有渐变类型为radial时才使用
    • android:useLevel如果为true,则可在LevelListDrawable中使用
  • corners: 设置圆角,只适用于rectangle类型
    • android:radius圆角半径,会被下面每个特定的圆角属性重写
    • android:topLeftRadius左上角的半径
    • android:topRightRadius右上角的半径
    • android:bottomLeftRadius左下角的半径
    • android:bottomRightRadius右下角的半径
  • stroke: 设置描边,可描成实线或虚线
    • android:color描边的颜色
    • android:width描边的宽度
    • android:dashWidth设置虚线时的横线长度
    • android:dashGap设置虚线时的横线之间的距离
  • size: 设置形状默认的大小,可设置宽度和高度
    • android:width宽度
    • android:height高度

line主要用于画分割线,是通过stroke和size特性组合来实现的,画线时,有几点特性必须要知道的:

  1. 只能画水平线,画不了竖线;
  2. 线的高度是通过stroke的android:width属性设置的;
  3. size的android:height属性定义的是整个形状区域的高度;
  4. size的height必须大于stroke的width,否则,线无法显示;
  5. 线在整个形状区域中是居中显示的;
  6. 线左右两边会留有空白间距,线越粗,空白越大;
  7. 引用虚线的view需要添加属性android:layerType,值设为”software”,否则显示不了虚线。

shape根元素有些属性只适用于ring类型:

  • android:innerRadius内环的半径
  • android:innerRadiusRatio浮点型,以环的宽度比率来表示内环的半径,默认为3,表示内环半径为环的宽度除以3,该值会被android:innerRadius覆盖
  • android:thickness环的厚度
  • android:thicknessRatio浮点型,以环的宽度比率来表示环的厚度,默认为9,表示环的厚度为环的宽度除以9,该值会被android:thickness覆盖
  • android:useLevel一般为false,否则可能环形无法显示,只有作为LevelListDrawable使用时才设为true

如果想让环形旋转起来,变成可用的进度条,则只要在shape外层包多一个rotate元素就可以了。

<?xml version="1.0" encoding="utf-8"?><rotate xmlns:android="http://schemas.android.com/apk/res/android"android:fromDegrees="0"android:pivotX="50%"android:pivotY="50%"android:toDegrees="360">···此处为shape代码段···</rotate>

本文参考:http://keeganlee.me/post/android/20150830