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

重寫 MPAndroidChart:解決 MarkView 在圖表邊緣被裁切的問題

編輯:關於 Android 程式設計

MPAndroidChart 是繪製圖表相當趁手的開源庫,多數常見需求都能覆蓋。但當你準備改造第三方元件時,比較好的做法始終是「繼承擴展」,而不是把原始碼整包複製到自己的專案裡——後者會讓後續升級變成一場噩夢。

實作過程中會遇到一個典型問題:MPAndroidChart 顯示標記(MarkView)時,若高亮點落在圖表靠近邊緣的位置,標記會被畫布裁掉一部分,顯示不全。本文記錄如何用繼承的方式繞過這個限制。

思路:繼承 LineChart,自己接管標記繪製

關鍵有兩點:把 LineChart 內部的 protected 方法 getMarkerPosition() 以 public 方法導出來取得高亮點座標;再重寫 drawMarkers(),在繪製前放寬 canvas 的裁剪區域,並對 Y 座標做一次偏移補償。

/**
 * 數據中心的折線圖,繼承 MPChart 的 LineChart
 * Created by wangchenlong on 15/10/13.
 */
public class CYDataLineChart extends LineChart {

    @SuppressWarnings("unused")
    private static final String TAG = "DEBUG-WCL: " + CYDataLineChart.class.getSimpleName();

    public CYDataLineChart(Context context) {
        super(context);
    }

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

    public CYDataLineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /** 把父類的 protected 方法導出,取得高亮點座標 */
    public float[] getHighLightPos(Entry e, Highlight highlight) {
        return getMarkerPosition(e, highlight);
    }

    /** 重寫標記繪製,修復邊緣裁切問題 */
    @Override
    protected void drawMarkers(Canvas canvas) {
        if (mMarkerView == null || !mDrawMarkerViews || !valuesToHighlight()) {
            return;
        }

        // 把裁剪區域向外擴展,避免標記被畫布邊緣切掉
        Rect newRect = canvas.getClipBounds();
        newRect.inset(-80, 0);
        canvas.clipRect(newRect, Region.Op.REPLACE);

        for (int i = 0; i < mIndicesToHighlight.length; i++) {

            Highlight highlight = mIndicesToHighlight[i];
            int xIndex = highlight.getXIndex();

            if (xIndex <= mDeltaX && xIndex <= mDeltaX * mAnimator.getPhaseX()) {

                Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]);
                if (e == null || e.getXIndex() != mIndicesToHighlight[i].getXIndex()) {
                    continue;
                }

                float[] pos = getMarkerPosition(e, highlight);

                // 重新計算 Y 座標,讓標記稍微偏離原始位置
                float tmpY = pos[1] - 8 * AppUtils.getPerDp();

                Paint paint = new Paint();
                paint.setStyle(Paint.Style.FILL);
                paint.setAntiAlias(true);
                paint.setStrokeWidth(5);
                paint.setColor(getResources().getColor(R.color.chart_circle));
                canvas.drawCircle(pos[0], pos[1], 2 * AppUtils.getPerDp(), paint);

                if (!mViewPortHandler.isInBounds(pos[0], tmpY)) {
                    continue;
                }

                mMarkerView.refreshContent(e, highlight);
                mMarkerView.measure(
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                mMarkerView.layout(0, 0,
                        mMarkerView.getMeasuredWidth(),
                        mMarkerView.getMeasuredHeight());

                // 若頂部空間不足,把標記翻到高亮點下方
                if (tmpY - mMarkerView.getHeight() <= 0) {
                    float y = mMarkerView.getHeight() - tmpY;
                    mMarkerView.draw(canvas, pos[0], tmpY + y);
                } else {
                    mMarkerView.draw(canvas, pos[0], tmpY);
                }
            }
        }
    }
}

getMarkerPosition 是 LineChart 中的 protected 方法,繼承類可以用 public 方法把它導出;float tmpY = pos[1] - 8 * AppUtils.getPerDp(); 這一行則是重新計算 Y 座標,讓標記偏離原始畫布位置,避免壓住折線本身。

遺留問題:移動標記時父容器出現殘影

上面的做法解決了裁切,卻帶來副作用——標記移動時,父容器上會留下上一幀的痕跡。原因是標記畫在子 View 的 canvas 上,而父容器並未跟著刷新。解法很直接:在標記位置變動時,順手讓父容器重繪。

// 設定圖表點擊事件,監聽高亮位置
mLcChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        int index = e.getXIndex();
        Log.e(TAG, "index = " + index);
        setChartIndex(index);
        mCallback.setCurIndex(index);
        mIndex = index;

        float[] pos = mLcChart.getHighLightPos(e, h);
        Log.e(TAG, "x: " + pos[0] + ", y: " + pos[1]);

        mLlContainer.invalidate(); // 重繪父容器,避免殘留
    }

    @Override
    public void onNothingSelected() {
        // 再次點擊時會呼叫,這裡維持非高亮狀態
        mLcChart.highlightValue(mIndex, 0);
    }
});
// 外部主動設定圖表高亮
private void setChartHighlight(int index) {
    if (mLcChart.getData() == null) {
        return;
    }
    mMarkerView.setDateText(mMarkers.get(index));
    mLcChart.highlightValue(index, 0);
    mLlContainer.invalidate(); // 重繪父容器,避免殘留
}

要注意的是,高亮位置可能由內部點擊觸發,也可能由外部程式碼觸發,兩條路徑都得記得呼叫 invalidate()。

至此,標記在邊緣顯示不全、以及移動殘影兩個問題都收拾乾淨了。改第三方庫時不妨記住這個原則:能繼承就不要複製,把差異集中在一個子類裡,升級時才不會痛苦。

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