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

Android 自定義 View:實現理財 App 七日年化收益折線圖

編輯:關於 Android 程式設計

這段時間學習自定義 View,陸續畫過柱狀圖、折線圖與進度控件。今天要聊的是理財類 App 中常見的「七日年化收益折線圖」。先看看效果。

效果圖中元素不少:線、柱狀底紋、文字、折線、點等等。看起來複雜,但只要一步一步來並不難。自定義 View 就像在 Photoshop 裡畫圖,想要什麼就畫什麼,有各種畫筆,也可以有很多圖層。

一、成員變量

private Paint mTextPaint, mLinePaint, mPathPaint, mPointPaint; // 各類畫筆
private float mPaintRectWidth;   // 柱狀圖寬度
private Path mPath;              // 折線路徑
private float mWidth, mHeight;   // 寬高
private final float mCount = 6;  // 柱狀圖數量
private final float offsets = 1; // 偏移量
private float mRectHeight;
private List<Float> xline = new ArrayList<Float>(); // x 軸座標
private List<Float> yline = new ArrayList<Float>(); // y 軸座標
private float[] x = {2.46f, 2.45f, 2.44f, 2.43f, 2.42f, 2.41f, 2.40f}; // 左側文字
private String[] day = {"07-01", "07-02", "07-03", "07-04", "07-05", "07-06", "07-07"}; // 底部日期

這裡涵蓋了文字、數據等幾乎全部所需變量。

二、初始化畫筆

private void initView() {
    // 文字與線的畫筆
    mTextPaint = new Paint();
    mTextPaint.setAntiAlias(true);
    mTextPaint.setColor(Color.parseColor("#cccccc"));
    mTextPaint.setTextSize(25);
    mTextPaint.setStrokeWidth(1);
    // 折線圖的點
    mPointPaint = new Paint();
    mPointPaint.setAntiAlias(true);
    mPointPaint.setColor(Color.parseColor("#000000"));
    mPointPaint.setTextSize(25);
    mPointPaint.setStrokeWidth(5);
    // 柱狀圖的畫筆
    mLinePaint = new Paint();
    mLinePaint.setAntiAlias(true);
    // 折線圖的畫筆
    mPathPaint = new Paint();
    mPathPaint.setAntiAlias(true);
    mPathPaint.setColor(Color.parseColor("#ff0000"));
    mPathPaint.setStyle(Style.STROKE);
    // 折線路徑
    mPath = new Path();
}

每支畫筆的顏色與寬度都不同,值得注意的是這裡並沒有設置镂空樣式。

三、在 onSizeChanged() 中賦值

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mWidth = (float) (getWidth() - getWidth() * 0.1);
    mHeight = (float) (getHeight() - getHeight() * 0.1);
    mRectHeight = (float) (getHeight() - getHeight() * 0.1);
    mPaintRectWidth = (float) (mWidth * 0.8 / mCount);
    mLinePaint.setStrokeWidth(mPaintRectWidth);
}

這裡刻意對寬高做了留白處理(各減去 10%),以提升頁面舒適度與用戶體驗。

四、onDraw() 的三大步驟

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    onDrawRect(canvas);   // 畫矩形底紋
    onDrawLine(canvas);   // 畫網格線
    canvasPath(canvas);   // 畫折線
}

從方法名就能看出三個職責,接下來看具體實現。

1. 繪製矩形底紋

private void onDrawRect(Canvas canvas) {
    for (int i = 0; i < 7; i++) {
        if (i % 2 == 0) {
            mLinePaint.setColor(Color.parseColor("#eeeeee"));
        } else {
            mLinePaint.setColor(Color.parseColor("#ece1f3"));
        }
        float left = (float) (mWidth * 0.4 / 2 + mPaintRectWidth * i + offsets);
        float right = (float) (mWidth * 0.4 / 2 + mPaintRectWidth * (i + 1));
        canvas.drawRect(left, (float) (mRectHeight * 0.01), right, mHeight, mLinePaint);
    }
}

2. 繪製網格線與座標文字

private void onDrawLine(Canvas canvas) {
    // 第一條線
    canvas.drawLine(mPaintRectWidth - mPaintRectWidth / 2, (float) (mRectHeight * 0.01),
            getWidth(), (float) (mRectHeight * 0.01), mTextPaint);
    float height;
    // 橫向七條
    for (float i = 0; i < 7; i++) {
        if (i == 0) {
            height = i;
        } else {
            height = mRectHeight * (i / 6);
            float size = mTextPaint.measureText(x[(int) i] + "");
            canvas.drawLine(mPaintRectWidth + mPaintRectWidth / 2, height, getWidth(), height, mTextPaint);
            // 左側 Y 軸文字
            canvas.drawText(x[(int) i] + "", (float) (mPaintRectWidth - mPaintRectWidth * 0.35),
                    height + size / 5, mTextPaint);
        }
    }
    // 縱向七條
    canvas.drawLine((float) (mPaintRectWidth - mPaintRectWidth / 2), 0,
            (float) (mPaintRectWidth - mPaintRectWidth / 2), mHeight, mTextPaint);
    for (float i = 0; i < 7; i++) {
        canvas.drawLine((float) (mWidth * 0.4 / 2 + mPaintRectWidth * i), 0,
                (float) (mWidth * 0.4 / 2 + mPaintRectWidth * i), mHeight, mTextPaint);
        // 底部日期文字
        canvas.drawText(day[(int) i], (float) (mWidth * 0.34 / 2 + mPaintRectWidth * i),
                (float) (mHeight + mHeight * 0.1), mTextPaint);
        // 準備折線圖的 x 軸座標
        xline.add((float) (mWidth * 0.4 / 2 + mPaintRectWidth * i));
    }
    // 折線圖的第一個點
    xline.add((float) (mPaintRectWidth - mPaintRectWidth / 2));
}

3. 繪製折線、點與文字

public void canvasPath(Canvas canvas) {
    for (int j = 0; j < yline.size(); j++) {
        float x = xline.get(j);
        float y = yline.get(j);
        float aftery = Math.initData(y);
        if (j == 0) {
            mPath.moveTo(x, aftery);
        } else {
            mPath.lineTo(x, aftery);
        }
        canvas.drawPoint(x, aftery, mPointPaint);
        float size = mPointPaint.measureText(y + "");
        canvas.drawText(y + "", (float) (x - size / 2), (float) (aftery + size * 0.25), mPointPaint);
    }
    canvas.drawPath(mPath, mPathPaint);
}

五、對外暴露的方法與座標轉換

// 設置 Y 軸座標值
public void setDataY(List<Float> yline) {
    this.yline.clear();
    this.yline = yline;
}
// 更新 UI
public void invalidata() {
    invalidate();
}

文字的換算則交由一個工具類處理:

public static float initData(float a) {
    if (2.40f <= a && a < 2.41f) {
        a = 540f - 540f / (a / 0.01f);
    } else if (2.41f <= a && a < 2.42f) {
        a = 480f - 480f / (a / 0.01f);
    } else if (2.42f <= a && a < 2.43f) {
        a = 360f - 360f / (a / 0.01f);
    } else if (2.43f <= a && a < 2.44f) {
        a = 270f - 270f / (a / 0.01f);
    } else if (2.44f <= a && a < 2.45f) {
        a = 180f - 180f / (a / 0.01f);
    } else if (2.45f <= a && a < 2.46f) {
        a = 90f - 90f / (a / 0.01f);
    }
    return a;
}

六、在 Activity 中使用

public class MainActivity extends Activity {
    private AnnualyieldView annualyieldView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        annualyieldView = (AnnualyieldView) findViewById(R.id.line);
        initdata();
    }
    private void initdata() {
        List<Float> yline = new ArrayList<Float>();
        yline.add(2.420123f);
        yline.add(2.444122f);
        yline.add(2.45359f);
        yline.add(2.4206f);
        yline.add(2.4357f);
        yline.add(2.4228f);
        yline.add(2.4350f);
        annualyieldView.setDataY(yline);
    }
}

布局文件 activity_main.xml:

<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    tools:context="com.example.annualyield.MainActivity"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">

    <LinearLayout
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="七日年化收益率(%)"
            android:textColor="#888888"
            android:textSize="18sp" />

        <com.example.annualyield.AnnualyieldView
            android:id="@+id/line"
            android:layout_height="200dip"
            android:layout_marginBottom="10dip"
            android:layout_marginTop="10dip"
            android:layout_width="match_parent" />
    </LinearLayout>
</RelativeLayout>

以上就是完整實現。記得大學時老師常說,不懂的地方就多敲代碼,敲多了自然就懂了——現在回想頗有道理。願與大家一起進步。

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