Android自定義分割線

每個App都會用到分割線,一個兩邊頂?shù)筋^的分割線只需要使用<View>配合background屬性就能夠輕松實現(xiàn)。
常見的分割線形式還有如下這種兩端或者一端留出一定空白距離的分割線。



實現(xiàn)這種效果有很多解決方案,我能想到的有三種:

第一種,也是最簡單的一種實現(xiàn)方式是:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="@dimen/divider_height"
    android:background="@android:color/white"
    android:paddingLeft="@dimen/divider_padding"
    android:paddingRight="@dimen/divider_padding">
    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent" 
        android:background="@android:color/white"/>
</LinearLayout>

這種實現(xiàn)方式會引起不必要的overdraw,因為容器的背景繪制了一次,然后分割線再繪制了一次。

第二種,可以用三個不同background的<View>來避免overdraw

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="@dimen/divider_height"
    android:orientation="horizontal">
    <View
        android:layout_width="@dimen/divider_padding"
        android:layout_height="match_parent" 
        android:background="@android:color/white"/>
    <View
        android:layout_width="@dimen/divider_padding"
        android:layout_height="match_parent" 
        android:layout_weight="1.0"
        android:background="@color/divider_color"/>
    <View
        android:layout_width="@dimen/divider_padding"
        android:layout_height="match_parent" 
        android:background="@android:color/white"/>
</LinearLayout>    

這個方案解決了overdraw問題,但也并非完美,因為為了實現(xiàn)分割線增加了一層嵌套。那么接下來就引出了本篇想要記錄的重點

第三種,自定義View繪制分割線

這樣最終分割線的布局代碼非常簡練:

<Divider
    android:layout_width="match_parent"
    android:layout_height="@dimen/divider_height"
    custom:dividerLineColor="@color/divider_color"
    custom:dividerPaddingLeft="@dimen/divider_padding"
    custom:dividerPaddingRight="@dimen/divider_padding" />

具體自定義View的細節(jié)不做詳細記錄,這里只記錄一下在canvas上畫線的重點代碼

@Override
protected void onDraw(Canvas canvas){
    Paint paint = new Paint();
    // canvas的寬度和高度
    int lineWidth = getWidth();
    int lineHeight = getHeight();
    // 設(shè)置線的粗細為canvas的高度
    paint.setStrokeWidth(lineHeight);  
    // 畫左端的白線,假設(shè)兩端留白長度是30
    paint.setColor(Color.WHITE); 
    canvas.drawLine(0, lineHeight/2, 30, lineHeight/2, paint);
    // 畫中間的分割線
    paint.setColor(Color.BLACK); 
    canvas.drawLine(30, lineHeight/2, lineWidth-30, lineHeight/2, paint);
    // 畫右端的白線,假設(shè)兩端留白長度是30
    paint.setColor(Color.WHITE); 
    canvas.drawLine(lineWidth-30, lineHeight/2, lineWidth, lineHeight/2, paint);
}

上面代碼的關(guān)鍵是
1、畫線方法:drawLine方法的前四個參數(shù)組成了兩組坐標,參數(shù)和坐標的關(guān)系如下圖:



2、上面的代碼中的startY和stopY都是lineHeight/2,這代表了兩層含義
(1)畫的是一條水平的線
(2)分割線的寬度,是從中間往上下兩側(cè)擴散的
所以設(shè)置startY、stopY為lineHeight/2之后,這條線就處于canvas的垂直中間位置,如果再設(shè)置線寬度為canvas的高度,那么這個時候line的高度就正好占滿了canvas的高度


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容