Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂控制項實作:畫出虛線(一)

編輯:關於 Android 程式設計

在 Android 中,要畫實線可以利用 View 搭配底色與 1px 的長度或寬度來進行佈局配置;但對於虛線,系統並沒有提供現成的控制項,也沒有比較好的既有元件實作方式。想要實現虛線,基本上有兩種途徑:一種是利用圖片,另一種則是利用畫布直接繪製。本文介紹第二種,也就是透過 Canvas 來繪製虛線。

首先定義一個繼承自 View 的類別,在 onDraw 方法中利用畫布畫出虛線:

package cn.emag.utils.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.util.AttributeSet;
import android.view.View;

public class CustomDashedLineView extends View {

 public CustomDashedLineView(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 @SuppressLint("DrawAllocation")
 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  Paint paint = new Paint();
  paint.setStyle(Paint.Style.STROKE);
  paint.setColor(getResources().getColor(Color.BLACK));
  Path path = new Path();
  path.moveTo(0, 5);
  path.lineTo(this.getWidth(), 5);
  // 透過 DashPathEffect 設定虛線的樣式,陣列中的數值分別代表實線與間隔的長度
  PathEffect effects = new DashPathEffect(new float[] { 5, 5, 5, 5 }, 1);
  paint.setPathEffect(effects);
  canvas.drawPath(path, paint);
 }
}

接著在版面配置中直接使用這個自訂 View:

<cn.emag.gaoju.view.DashedLineView
            android:layout_width="match_parent"
            android:layout_height="10dp">
</cn.emag.gaoju.view.DashedLineView>

關鍵在於 DashPathEffect,它能指定虛線中實線段與空白間隔的長度,藉此產生不同的虛線樣式。由於各個應用的需求不盡相同,虛線的樣式也可以進一步透過自訂屬性把參數傳入來控制,這裡就不再展開說明。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved