android開發 畫虛線

2021-08-07 14:08:16 字數 1857 閱讀 3558

public

class

dashview

extends

view

public

dashview(context context, attributeset attrs)

@override

protected

void

onmeasure(int widthmeasurespec, int heightmeasurespec) else

}@override

protected

void

ondraw(canvas canvas)

}/**

* 畫水平方向虛線

*@param canvas

*/public

void

drawhorizontalline(canvas canvas);

//在畫線之前需要先把畫布向下平移辦個線段高度的位置,目的就是為了防止線段只畫出一半的高度

canvas.translate(0,lineheight/2);

while(totalwidth<=widthsize)

canvas.restore();

}/**

* 畫豎直方向虛線

*@param canvas

*/public

void

drawverticalline(canvas canvas);

//在畫線之前需要先把畫布向右平移半個線段高度的位置,目的就是為了防止線段只畫出一半的高度

canvas.translate(lineheight/2,0);

while(totalwidth<=heightsize)

canvas.restore();

}}

**中用到了自定義屬性,在res的values中新建attrs.xml,編寫如下:

name="dashview">

name="dashwidth"

format="dimension"/>

name="linewidth"

format="dimension"/>

name="lineheight"

format="dimension"/>

name="linecolor"

format="color"/>

name="dashorientation"

format="integer"/>

declare-styleable>

配置完成,在布局中呼叫即可

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginleft="10dp"

android:layout_marginright="10dp"

其中,屬性介紹:

dashwidth:兩段線段之間的間距

linewidth:每條線段寬度

linecolor:線段顏色

dashorientation:虛線方向 0,水平,1,豎直

lineheight:線段高度

注意:注意事項 當設定虛線的方向時,對應方向的wrap_content顯示效果為match_parent,因為在實際情況中,虛線的尺寸總是固定的數值。

再次注意:本文是在其他開發者**的基礎上進行整理的,我感覺好用並且實用,比找美工給切乙個虛線的要省記憶體。現在附上原作者部落格鏈結和git位址

csdn:

github:

再次感謝 原作者!

Android之畫虛線技巧

ui設計圖中,經常需要畫水平和豎直的虛線,本文實現虛線效果。在drawable中建立dash horizontal view.xml檔案 在布局中引用這個shape檔案,完成水平虛線的繪製。有幾個關鍵點 dashwidth 是指虛線中每乙個實線的寬度,dashgap 是指虛線中每乙個間隔的寬度,如果...

iOS開發畫虛線的方法

cashapelayer shapelayer cashapelayer layer shapelayer setbounds self.view.bounds shapelayer setposition self.view.center shapelayer setfillcolor uicol...

Android 畫虛線顯示實線的BUG

畫虛線一般寫個xml 其中dashgap是空隙寬度,dashwidth是線的寬度,當dashgap也就是空隙寬度為0時,顯示一條實線。然後在background或src中引用,但在android 4.0以上版本中會有bug,發現不管dashgap設定多大,顯示的都是一條實線。解決方法 關閉硬體加速。...