繪制虛線的幾種方式

方式一:利用shape繪制

xml布局

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@drawable/shape_dash"
    android:layerType="software" />

shape_dash.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="3px"
        android:color="#FF0000"
        android:dashWidth="10px"
        android:dashGap="10px" />
</shape>

方式二:自定義View繪制虛線允青,drawLines實現(xiàn)

xml布局

<com.jianshu.DashView
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layout_marginTop="10dp"
    app:dashWidth="5dp"
    app:lineColor="@color/colorPrimary"
    app:lineHeight="2dp"
    app:lineWidth="5dp" />

自定義view:

public class DashView extends View {
    private static final String TAG = "DashView";
    public static final int DEFAULT_DASH_WIDTH = 100;
    public static final int DEFAULT_LINE_WIDTH = 100;
    public static final int DEFAULT_LINE_HEIGHT = 10;
    public static final int DEFAULT_LINE_COLOR = 0x9E9E9E;

    /**虛線的方向*/
    public static final int ORIENTATION_HORIZONTAL = 0;
    public static final int ORIENTATION_VERTICAL = 1;
    /**默認為水平方向*/
    public static final int DEFAULT_DASH_ORIENTATION = ORIENTATION_HORIZONTAL;
    /**間距寬度*/
    private float dashWidth;
    /**線段高度*/
    private float lineHeight;
    /**線段寬度*/
    private float lineWidth;
    /**線段顏色*/
    private int lineColor;
    private int dashOrientation;

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int widthSize;
    private int heightSize;

    public DashView(Context context) {
        this(context,null);
    }

    public DashView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.DashView);
        dashWidth = typedArray.getDimension(R.styleable.DashView_dashWidth,DEFAULT_DASH_WIDTH);
        lineHeight = typedArray.getDimension(R.styleable.DashView_lineHeight, DEFAULT_LINE_HEIGHT);
        lineWidth = typedArray.getDimension(R.styleable.DashView_lineWidth, DEFAULT_LINE_WIDTH);
        lineColor = typedArray.getColor(R.styleable.DashView_lineColor, DEFAULT_LINE_COLOR);
        dashOrientation = typedArray.getInteger(R.styleable.DashView_dashOrientation,DEFAULT_DASH_ORIENTATION);
        mPaint.setColor(lineColor);
        mPaint.setStrokeWidth(lineHeight);
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        widthSize = MeasureSpec.getSize(widthMeasureSpec)-getPaddingLeft()-getPaddingRight();
        heightSize = MeasureSpec.getSize(heightMeasureSpec - getPaddingTop() - getPaddingBottom());
        Log.d(TAG, "onMeasure: "+widthSize+"----"+heightSize);
        Log.d(TAG, "dashOrientation: "+dashOrientation);
        if(dashOrientation == ORIENTATION_HORIZONTAL){
            //不管在布局文件中虛線高度設(shè)置為多少馍管,虛線的高度統(tǒng)一設(shè)置為實體線段的高度
            setMeasuredDimension(widthSize, (int) lineHeight);
        }else{
            setMeasuredDimension((int) lineHeight, heightSize);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        switch (dashOrientation){
            case ORIENTATION_VERTICAL:
                drawVerticalLine(canvas);
                break;
            default:
                drawHorizontalLine(canvas);
        }
    }

    /**
     * 畫水平方向虛線
     * @param canvas
     */
    public void drawHorizontalLine(Canvas canvas){
        float totalWidth = 0;
        canvas.save();
        float[] pts = {0,0,lineWidth,0};
        //在畫線之前需要先把畫布向下平移辦個線段高度的位置,目的就是為了防止線段只畫出一半的高度
        //因為畫線段的起點位置在線段左下角
        canvas.translate(0,lineHeight/2);
        while(totalWidth<=widthSize){
            canvas.drawLines(pts,mPaint);
            canvas.translate(lineWidth + dashWidth,0);
            totalWidth += lineWidth + dashWidth;
        }
        canvas.restore();
    }

    /**
     * 畫豎直方向虛線
     * @param canvas
     */
    public void drawVerticalLine(Canvas canvas){
        float totalWidth = 0;
        canvas.save();
        float[] pts = {0,0,0,lineWidth};
        //在畫線之前需要先把畫布向右平移半個線段高度的位置洪橘,目的就是為了防止線段只畫出一半的高度
        //因為畫線段的起點位置在線段左下角
        canvas.translate(lineHeight/2,0);
        while(totalWidth<=heightSize){
            canvas.drawLines(pts,mPaint);
            canvas.translate(0,lineWidth + dashWidth);
            totalWidth += lineWidth + dashWidth;
        }
        canvas.restore();
    }

}

方式三:自定義View繪制虛線,drawPath實現(xiàn)

xml布局

    <com.jianshu.DashView2
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_marginTop="10dp"
        app:dashOrientation="1"
        app:dashWidth="10dp"
        app:lineColor="@color/colorPrimary"
        app:lineHeight="200dp"
        app:lineWidth="400dp" />

自定義view:

public class DashView2 extends View {
    private Paint mPaint;
    private Path mPath;

    public DashView2(Context context) {
        this(context, null);
    }

    public DashView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(0xffff0000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(3);
        //設(shè)置繪制路徑的效果
        mPaint.setPathEffect(new DashPathEffect(new float[]{15, 5},0));
        mPath = new Path();
        mPath.addCircle(0, 0, 3, Path.Direction.CW);
        mPaint.setPathEffect(new PathDashPathEffect(mPath, 15, 0, PathDashPathEffect.Style.ROTATE));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //設(shè)置漸變色,選用
//        mPaint.setShader(new LinearGradient(0, 0, getWidth(), 0,
//                new int[]{Color.TRANSPARENT, Color.BLACK, Color.BLACK, Color.TRANSPARENT},
//                new float[]{0, 0.3f, 0.7f, 1f}, Shader.TileMode.CLAMP));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int centerY = getHeight() / 2;
        mPath.reset();
        mPath.moveTo(0, centerY);
        mPath.lineTo(getWidth(), centerY);
        canvas.drawPath(mPath, mPaint);
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末俄讹,一起剝皮案震驚了整個濱河市公黑,隨后出現(xiàn)的幾起案子邑商,更是在濱河造成了極大的恐慌,老刑警劉巖凡蚜,帶你破解...
    沈念sama閱讀 218,640評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件人断,死亡現(xiàn)場離奇詭異,居然都是意外死亡番刊,警方通過查閱死者的電腦和手機含鳞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芹务,“玉大人蝉绷,你說我怎么就攤上這事鸭廷。” “怎么了熔吗?”我有些...
    開封第一講書人閱讀 165,011評論 0 355
  • 文/不壞的土叔 我叫張陵辆床,是天一觀的道長。 經(jīng)常有香客問我桅狠,道長讼载,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評論 1 294
  • 正文 為了忘掉前任中跌,我火速辦了婚禮咨堤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘漩符。我一直安慰自己一喘,他們只是感情好,可當我...
    茶點故事閱讀 67,774評論 6 392
  • 文/花漫 我一把揭開白布嗜暴。 她就那樣靜靜地躺著凸克,像睡著了一般。 火紅的嫁衣襯著肌膚如雪闷沥。 梳的紋絲不亂的頭發(fā)上萎战,一...
    開封第一講書人閱讀 51,610評論 1 305
  • 那天,我揣著相機與錄音舆逃,去河邊找鬼蚂维。 笑死,一個胖子當著我的面吹牛颖侄,可吹牛的內(nèi)容都是我干的鸟雏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,352評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼览祖,長吁一口氣:“原來是場噩夢啊……” “哼孝鹊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起展蒂,我...
    開封第一講書人閱讀 39,257評論 0 276
  • 序言:老撾萬榮一對情侶失蹤又活,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后锰悼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體柳骄,經(jīng)...
    沈念sama閱讀 45,717評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,894評論 3 336
  • 正文 我和宋清朗相戀三年箕般,在試婚紗的時候發(fā)現(xiàn)自己被綠了耐薯。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,021評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖曲初,靈堂內(nèi)的尸體忽然破棺而出体谒,到底是詐尸還是另有隱情,我是刑警寧澤臼婆,帶...
    沈念sama閱讀 35,735評論 5 346
  • 正文 年R本政府宣布抒痒,位于F島的核電站,受9級特大地震影響颁褂,放射性物質(zhì)發(fā)生泄漏故响。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,354評論 3 330
  • 文/蒙蒙 一颁独、第九天 我趴在偏房一處隱蔽的房頂上張望彩届。 院中可真熱鬧,春花似錦奖唯、人聲如沸惨缆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至寂汇,卻和暖如春病往,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背骄瓣。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評論 1 270
  • 我被黑心中介騙來泰國打工停巷, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人榕栏。 一個月前我還...
    沈念sama閱讀 48,224評論 3 371
  • 正文 我出身青樓畔勤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親扒磁。 傳聞我的和親對象是個殘疾皇子庆揪,可洞房花燭夜當晚...
    茶點故事閱讀 44,974評論 2 355

推薦閱讀更多精彩內(nèi)容