Android开发之ShapeDrawable

Android开发之ShapeDrawable

/*

* Android开发之ShapeDrawble

* 北京Android俱乐部群:167839253

* Created on: 2011-12-6

* Author: blueeagle

* Email: liujiaxiang@gmail.com

*/

引用一下ShapeDrawable的类的说明:

java.lang.Object

?

android.graphics.drawable.Drawable

?

android.graphics.drawable.ShapeDrawable

ClassOverview
ADrawableobjectthatdrawsprimitiveshapes.AShapeDrawabletakesaShapeobjectandmanagesitspresenceonthescreen.
IfnoShapeisgiven,thentheShapeDrawablewilldefaulttoaRectShape.
ItcanbedefinedinanXMLfilewiththe<shape>element.
filelocation:
res/drawable/filename.xml
ThefilenameisusedastheresourceID.
compiledresourcedatatype:
ResourcepointertoaShapeDrawable.
resourcereference:
InJava:R.drawable.filename
InXML:@[package:]drawable/filename

Android中,利用ShapeDrawable来绘制图像,ShapeDrawable可以设置画笔的形状。通过geiPaint方可以得到Paint对象。

利用ShapeDrawable在代码中画图像的步骤如下:

1. 实例化ShapeDrawable对象,并说明绘制的形状;

a) 形状可以是矩形,椭圆,线和环(例如椭圆:)

       myShapeDrawable = new ShapeDrawable(new OvalShape());
       //得到画笔Paint对象并设置其颜色
       myShapeDrawable.getPaint().setColor(Color.GREEN);
       myShapeDrawable.setBounds(70,250,150,280);
       //绘制图像
       myShapeDrawable.draw(canvas);

2. 得到画笔对象并设置其颜色;

3. 利用setBounds方法来设置图像显示的区域;

4. 在画布上绘制图像。

当然,也可以使用XML文件来定义画图,就是利用XML文件来定义一个图像。

具体语法如下:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape=["rectangle" | "oval" | "line" | "ring"] >
    <corners
        android:radius="integer"
        android:topLeftRadius="integer"
        android:topRightRadius="integer"
        android:bottomLeftRadius="integer"
        android:bottomRightRadius="integer" />
    <gradient
        android:angle="integer"
        android:centerX="integer"
        android:centerY="integer"
        android:centerColor="integer"
        android:endColor="color"
        android:gradientRadius="integer"
        android:startColor="color"
        android:type=["linear" | "radial" | "sweep"]
        android:usesLevel=["true" | "false"] />
    <padding
        android:left="integer"
        android:top="integer"
        android:right="integer"
        android:bottom="integer" />
    <size
        android:width="integer"
        android:height="integer" />
    <solid
        android:color="color" />
    <stroke
        android:width="integer"
        android:color="color"
        android:dashWidth="integer"
        android:dashGap="integer" />
</shape>

AndroidSDK中定义的规则:

elements:
<shape>
Theshapedrawable.Thismustbetherootelement.
attributes:
xmlns:android
String.Required.DefinestheXMLnamespace,whichmustbe"http://schemas.android.com/apk/res/android".
android:shape
Keyword.Definesthetypeofshape.Validvaluesare:

Value

Desciption

"rectangle"

A rectangle that fills the containing View. This is the default shape.

"oval"

An oval shape that fits the dimensions of the containing View.

"line"

A horizontal line that spans the width of the containing View. This shape requires the<stroke>element to define the width of the line.

"ring"

A ring shape.

矩形"rectangle",椭圆"oval",线"line"和环"ring"
当是线"line"的时候一定要定义<stroke>element
Thefollowingattributesareusedonlywhenandroid:shape="ring":
下面的属性只有在android:shape="ring"时才在有意义
android:innerRadius
Dimension.Theradiusfortheinnerpartofthering(theholeinthemiddle),
asadimensionvalueordimensionresource.
android:innerRadiusRatio
Float.Theradiusfortheinnerpartofthering,expressedasaratioofthering'swidth.
Forinstance,ifandroid:innerRadiusRatio="5",thentheinnerradiusequalsthering'swidthdividedby5.
Thisvalueisoverriddenbyandroid:innerRadius.Defaultvalueis9.
android:thickness
Dimension.Thethicknessofthering,asadimensionvalueordimensionresource.
android:thicknessRatio
Float.Thethicknessofthering,expressedasaratioofthering'swidth.
Forinstance,ifandroid:thicknessRatio="2",thenthethicknessequalsthering'swidthdividedby2.
Thisvalueisoverriddenbyandroid:innerRadius.Defaultvalueis3.
android:useLevel
Boolean."true"ifthisisusedasaLevelListDrawable.Thisshouldnormallybe"false"oryourshapemaynotappear.
<corners>
Createsroundedcornersfortheshape.Appliesonlywhentheshapeisarectangle.

该属性只有android:shape="rectangle";才有意义
attributes
:
android:radius
Dimension.Theradiusforallcorners,asadimensionvalueordimensionresource.
Thisisoverriddenforeachcornerbythefollowingattributes.
默认情况下四个角的半径,如果为0则表示直角
android:topLeftRadius
Dimension.Theradiusforthetop-leftcorner,asadimensionvalueordimensionresource.
左上角的半径
android:topRightRadius
Dimension.Theradiusforthetop-rightcorner,asadimensionvalueordimensionresource.
右上角的半径
android:bottomLeftRadius
Dimension.Theradiusforthebottom-leftcorner,asadimensionvalueordimensionresource.
左下角的半径
android:bottomRightRadius
Dimension.Theradiusforthebottom-rightcorner,asadimensionvalueordimensionresource.
右下角的半径
Note:Everycornermust(initially)beprovidedacornerradiusgreaterthan1,orelsenocornersarerounded.
Ifyouwantspecificcornerstonotberounded,awork-aroundistouseandroid:radiusto
setadefaultcornerradiusgreaterthan1,butthenoverrideeachandeverycornerwiththevaluesyoureallywant,
providingzero("0dp")whereyoudon'twantroundedcorners.
<gradient>
Specifiesagradientcolorfortheshape.
该系列属性对线"line"没有意义。

attributes:
android:angle
Integer.Theangleforthegradient,indegrees.0islefttoright,90isbottomtotop.
Itmustbeamultipleof45.Defaultis0.
颜色的变化方式,0表示从左到右,90表示从下到上,45表示在从左到右和从下到上同时进行
发现该属性只有android:type="linear"才有用。
android:centerX
Float.TherelativeX-positionforthecenterofthegradient(0-1.0).Doesnotapplywhenandroid:type="linear".
中心点在x方向上的值,其值为0-1.0
其x=x0+(x1-x0)*centerX.
当android:type="linear"时没有意义
android:centerY
Float.TherelativeY-positionforthecenterofthegradient(0-1.0).Doesnotapplywhenandroid:type="linear".
中间点在y方向上的值,其值为0-1.0
其y=y0+(y1-y0)*centerY.
当android:type="linear"时没有意义
android:centerColor
Color.Optionalcolorthatcomesbetweenthestartandendcolors,asahexadecimalvalueorcolorresource.
中间点的Color
android:endColor
Color.Theendingcolor,asahexadecimalvalueorcolorresource.
终点的gradient颜色
android:gradientRadius
Float.Theradiusforthegradient.Onlyappliedwhenandroid:type="radial".
中心园的半径,只有当android:type="radial"时有意义
android:startColor
Color.Thestartingcolor,asahexadecimalvalueorcolorresource.
起始点gradient的颜色
android:type
Keyword.Thetypeofgradientpatterntoapply.Validvaluesare:
ValueDescription
"linear"Alineargradient.Thisisthedefault.线性
"radial"Aradialgradient.Thestartcoloristhecentercolor.发射型
"sweep"Asweepinglinegradient.
gradient有两个或三个颜色值
startColor中心区域的颜色
centerColor 中心区域的外环区域(中间)的颜色。它是可选的。
endColor 其他区域颜色
startColor和endColor的使用见实例2

startColor,centerColo和endColor的使用见实例4
android:useLevel
Boolean."true"ifthisisusedasaLevelListDrawable.
当为LevelListDrawable时其值为true否则为false
<padding>
PaddingtoapplytothecontainingViewelement(thispadsthepositionoftheViewcontent,nottheshape).
该属性用于设置ShapeDrawable的content区域的Padding。
ShapeDrawable的content区域用于确定他所在控件的content(通常是文本)的区域
attributes:
android:left
Dimension.Leftpadding,asadimensionvalueordimensionresource.
android:top
Dimension.Toppadding,asadimensionvalueordimensionresource.
android:right
Dimension.Rightpadding,asadimensionvalueordimensionresource.
android:bottom
Dimension.Bottompadding,asadimensionvalueordimensionresource.

<size>
Thesizeoftheshape.

attributes:

android:height
Dimension.Theheightoftheshape,asadimensionvalueordimensionresource.

该属性对线"line"没有意义。
android:width
Dimension.Thewidthoftheshape,asadimensionvalueordimensionresource.

Note:TheshapescalestothesizeofthecontainerViewproportionatetothedimensionsdefinedhere,bydefault.
WhenyouusetheshapeinanImageView,youcanrestrictscalingbysettingtheandroid:scaleTypeto"center".
ShapeDrawable的大小
注意当是线的时候<size>只有android:width属性意义了。

<solid>
Asolidcolortofilltheshape.
attributes:
android:color
Color.Thecolortoapplytotheshape,asahexadecimalvalueorcolorresource.
<solid>用(ahexadecimalvalueorcolorresource)来填充ShapeDrawable,这时gradient属性无意义
<stroke>
Astrokelinefortheshape.
attributes:
android:width
Dimension.Thethicknessoftheline,asadimensionvalueordimensionresource.
android:color
Color.Thecoloroftheline,asahexadecimalvalueorcolorresource.
android:dashGap
Dimension.Thedistancebetweenlinedashes,asadimensionvalueordimensionresource.Onlyvalidifandroid:dashWidthisset.
android:dashWidth
Dimension.Thesizeofeachdashline,asadimensionvalueordimensionresource.Onlyvalidifandroid:dashGapisset.
android:width表示边框线的宽度。边框是向里外同时扩展的。
android:color表示边框线的颜色
android:dashGap表示dash线之间的长度
android:dashWidth表示dash线的长度
注意:当android:shape="line"时必须定义<stroke>。这时ShapeDrawable的边框就只有一个边(line)

ThislayoutXMLappliestheshapedrawabletoaView:

<TextView
android:background="@drawable/gradient_box"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>

ThisapplicationcodegetstheshapedrawableandappliesittoaView:

Resourcesres=getResources();
Drawableshape=res.getDrawable(R.drawable.gradient_box);

TextViewtv=(TextView)findViewByID(R.id.textview);
tv.setBackground(shape);

举几个例子:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient 
        android:startColor="#FF0000FF" 
         android:centerColor="#FF00FF00"
        android:endColor="#FFFF0000"
        android:type="radial"
        android:gradientRadius="100"
        android:angle="90"/>
    <padding android:left="0dp" 
        android:top="0dp"
        android:right="0dp" 
        android:bottom="0dp" />
    <corners android:radius="0dp" android:topLeftRadius="0dp"/>
</shape>
实例2
drawable下的gradient_box.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient 
        android:startColor="#FF0000FF" 
        android:endColor="#FFFF0000"
        android:type="sweep"
        android:angle="90"/>
    <padding android:left="0dp" 
        android:top="0dp"
        android:right="0dp" 
        android:bottom="0dp" />
    <corners android:radius="80dp" android:topLeftRadius="10dp"/>
</shape>
实例3
drawable下的gradient_box.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient 
        android:startColor="#FF0000FF" 
         android:centerColor="#FF00FF00"
        android:endColor="#FFFF0000"
        android:type="sweep"
        android:angle="90"/>
    <padding android:left="0dp" 
        android:top="0dp"
        android:right="0dp" 
        android:bottom="0dp" />
    <corners android:radius="80dp" android:topLeftRadius="10dp"/>
</shape>
实例4
stroke的使用
drawable下的gradient_box.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient 
        android:startColor="#FF0000FF" 
         android:centerColor="#FF00FF00"
        android:endColor="#FFFF0000"
        android:type="radial"
        android:gradientRadius="100"/>
    <padding android:left="0dp" 
        android:top="0dp"
        android:right="0dp" 
        android:bottom="0dp" />
    <corners android:radius="10dp" android:topLeftRadius="0dp"/>
        <size
        android:width="150dp"
        android:height="150dp" />
        <stroke
            android:width="20dp"
            android:color="#FF0000FF"
            android:dashWidth="1dp"
            android:dashGap="1dp" />
</shape>
实例5
椭圆
drawable下的gradient_box.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <gradient 
        android:startColor="#FF0000FF" 
        android:centerColor="#FF00FF00"
        android:endColor="#FFFF0000"
        android:type="radial"
        android:gradientRadius="100"/>
    <padding android:left="0dp" 
        android:top="0dp"
        android:right="0dp" 
        android:bottom="0dp" />
</shape>
实例6
线"line"的使用
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
        <size android:width="300dp"/>
        <stroke
            android:width="10dp"
            android:color="#FF0000FF"
            android:dashWidth="1dp"
            android:dashGap="1dp" />
</shape>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值