shape類似CSS,用于背景,邊框,便于相容各種螢幕和分辨率:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充色 -->
<solid android:color="#e4e4e4"/>
<!-- 描邊 -->
<stroke android:color="#e4e4e4" />
<!-- 圓角半徑 -->
<corners android:radius="4dip" />
<!-- 漸變 -->
<gradient
android:angle="45"
android:centerX="20dip"
android:centerColor="#ff0000"
android:startColor="#ffffff"
android:endColor="#000000"/>
<padding
android:left="10dip"/>
<size android:width="60dip"
android:height="30dip"/>
</shape>
shape屬性:
rectangle:矩形
oval:橢圓
line:線,需要 stroke 來設定寬度
ring:環形
solid屬性:
color:填充顔色
stroke屬性:
color:邊框顔色
width:邊框寬度
dashWidth:虛線框的寬度
dashGap:虛線框的間隔
corners屬性:
radius:四個角的半徑
topRightRadius:右上角的半徑
bottomLeftRadius:右下角的半徑
opLeftRadius:左上角的半徑
bottomRightRadius:左下角的半徑
gradient屬性:
startColor:其實顔色
centerColor:中間顔色
endColor:結束顔色
centerX:中間顔色的相對X坐标(0 -- 1)
centerY:中間顔色的相對Y坐标(0 -- 1)
useLevel:(true/false), 是否用作LevelListDrawable的标志
angle是漸變角度,必須為45的整數倍。0從左到右,90從下到上,180從右到左,270從上到下
type:漸變模式。 預設線性漸變,可以指定漸變為radial(徑向漸變)或者sweep(類似雷達掃描的形式)
gradientRadius:漸變半徑,徑向漸變需指定半徑。
padding屬性:
left:左内邊距
top:上内邊距
right:右内邊距
bottom:下内邊距
size屬性:
width:寬
height:高
下面是shape的應用:
android中實作自定義畫線,畫圓,畫矩形,使用自定義字型
一、自定義畫線
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line" >
<stroke android:width="1dp" //線的粗度
android:color="#33ccff" //顔色
android:dashWidth="2dp" //虛線的線段長度
android:dashGap="5dp"/> //虛線的間隔長度
</shape>
布局xml檔案中可以使用textview控件,設定背景屬性
二、自定義畫圓
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#33ccff"/>
<size android:width="50dp" //圓或橢圓
android:height="50dp"/>
</shape>
布局xml檔案中使用imageview控件
三、自定義畫矩形
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<gradient
android:angle="45" //漸變角度 45的整數倍
android:centerColor="#00ff00" //漸變顔色
android:endColor="#0000ff"
android:startColor="#ff0000" />
<solid android:color="#33ccff" /> //純色
<size
android:height="100dp"
android:width="50dp" />
<corners android:radius="10dp" /> //圓角
</shape>
四、使用自定義字型
把字型格式檔案.ttf,拷貝到assets目錄下,讀取字型檔案Typeface.createFromAsset,設定類型setTypeface
代碼中使用字型如下:
TextView textView = (TextView) findViewById(R.id.textView2);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/samplefont.ttf");//讀取字型
textView.setTypeface(tf);//設定字型