Android使用代碼方式靈活定義線條元素

2024年2月6日 19点热度 0人点赞

Android界面中實現畫線條,我們經常在drawable目錄下定義shape標簽的XML資源文件,然後設置為ImageView的src屬性,它可以方便地實現各種效果的虛線條和實線條。

但這種方式眾所周知的缺點是,shape標簽的XML資源文件會造成冗餘,也就是不同高度、不同顏色、不同虛線條的長度和間隔,我們都不得不定義不同的XML資源。不僅顯得資源冗餘,而且使得界面UI展現與資源文件的高耦合度。

這裡介紹另一種代碼動態生成Bitmap線條的方法。

代碼動態生成線條

我們知道,使用shape標簽定義線條時,它在stroke子標簽中需要聲明下面四個屬性:

  • android:width 表示線條高度
  • android:color 表示線條顏色
  • android:dashWidth 表示虛線條中,一個虛線段的長度
  • android:dashGap 表示虛線條中,虛線段之間的間隔長度

android:dashWidthandroid:dashGap都為0時,表示實線條。實線條生成相對簡單,下面重點分析虛線條的生成。

用代碼的方式動態生成線條,也需要這4個參數。

虛線條的dashWidth與dashGap參數

如上圖中,虛線條一般起始線條為實線段,實線段長度為dashWidth,然後間隔dashGap長度的空白,又接著是dashWidth長度的實線條,如此循環。

要用代碼動態生成線條,就需要計算出在一個長度為L的線條中的,任意一點的橫坐標值X(0<X<=L),是要顯示為空白(白色)還是線條的顏色。

通過分析,有如下的關系:

X滿足以下條件時,需要顯示為間隔空白:

int lineSegment = dashWidth   dashGap;
//X為橫坐標,虛線條繪制過程中,虛線段間隔空白的條件
((dashWidth   (X / lineSegment) * lineSegment) < X && X <= ((X / lineSegment) * lineSegment)   lineSegment)

否則,需要顯示為虛線段,也就是繪制為所設置的線條顏色。

所以,生成Bitmap線條的完整代碼為:

 /**
  * @param height 線條高度
  * @param width 線條長度
  * @param lineStyle 線條樣式:虛線|實線
  * @param lineColor 線條顏色
  */
private Bitmap createLine(int height, int width, String lineStyle, int dashWidth, int dashGap, int color) {
    int w = width, h = height;
    int[] pixels = new int[w * h];
    int lineSegment = dashWidth   dashGap;
    if (lineStyle.equals("dashed_line")) {
        //虛線
        for (int i = 0; i < h; i  ) {
            for (int x = 0; x < w; x  ) {
                if (((dashWidth   (x / lineSegment) * lineSegment) < x && x <= ((x / lineSegment) * lineSegment)   lineSegment)) {
                    pixels[i * w   x] = 0xFFFFFFFF;  //白色,表示虛線段之間的空白間隔
                } else {
                    pixels[i * w   x] = lineColor;  //線條顏色
                }
            }
        }
    } else {
        //實線
        for (int i = 0; i < h; i  ) {
            for (int x = 0; x < w; x  ) {
                pixels[i * w   x] = lineColor;
            }
        }
    }
    Bitmap mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mBitmap.setPixels(pixels, 0, w, 0, 0, w, h);
    return mBitmap;
}

這樣,當UI界面中需要展示線條元素時,隻需定義好ImageView,然後調用此方法生成Bitmap,使用ImageView的setImageBitmap()方法即可。

附上shape標簽定義線條

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <stroke
        android:width="2dp"
        android:color="#000000"
        android:dashWidth="4dp"
        android:dashGap="4dp" />
</shape>

當android:dashWidth和android:dashGap為0時表示實線。