android開發自訂View實現柱狀圖

來源:互聯網
上載者:User

為了使文章中的代碼看起來簡潔一點,便於理解一點,我就不把Paint的執行個體化代碼貼出來了,另外提示:本文所有變數都是我定死的,各位可以根據需求來自己設定getset方法.

參數:

private Paint mPaint;//畫文字和XY軸的畫筆
private Paint mPaintColumn;//畫圓柱的畫筆
private final float START_X = 200;//Y軸左上方X座標
private final float START_Y = 200;//Y軸左上方Y座標
private boolean canLoad = true;//是否開始畫圖
private float XSpace = 150;//Y軸每個數字間距
private float XWidth = 900;//X軸總長度
private String[] XNames = {"測試1", "測試2", "測試3", "測試4", "測試5"};
private int YCount = 10;//Y軸數值的個數(包括0)
private float YSpace = 100;//Y軸每個數字間距
private float YHeight = 1000;//Y軸總長度
private float ColumsWidth = 50;//長方形寬(圓柱)

YHeight = (float) (YHeight + getTxtHeight(mPaint));//這個代碼的意思是:將Y軸的值和文字高度加起來,因為文字有高度,如果
不算文字高度,最後一個Y軸的值就會比計劃高一點

//擷取文字的高
public double getTxtHeight(Paint mPaint) {
 Paint.FontMetrics fm = mPaint.getFontMetrics();
 return Math.ceil(fm.descent - fm.ascent);
}

關鍵代碼draw:

@Override
public void draw(Canvas canvas) {
    super.draw(canvas);
    if (canLoad) {
        canvas.drawLine(START_X, START_Y, START_X, YHeight + START_Y, mPaint);//Y軸
        canvas.drawLine(START_X, YHeight + START_Y, START_X + XWidth, YHeight + START_Y, mPaint);//X軸
        float MaxTextWidth = mPaint.measureText("1000");//這裡我知道最長的字為1000,所以這麼寫,根據不同情況改
        float TxtHeight = (float) getTxtHeight(mPaint);//mPaint所畫文字的高度
        //Y軸上的數值
        for (int i = 0; i <= YCount; i++) {
            String count = 100 * i + "";
            canvas.drawText(count, START_X - MaxTextWidth, YHeight + START_Y - YSpace * i, mPaint);
        }
        //X軸上的數值
        for (int i = 0; i < XNames.length; i++) {
            String name = XNames[i];
            canvas.drawText(name, START_X + XSpace * (i + 1), YHeight + START_Y + TxtHeight, mPaint);
        }
 
        //圓柱和圓柱上面的具體數值
        for (int i = 0; i < XNames.length; i++) {
            String count = (i + 1) * 100 + "";
            canvas.drawRect(START_X + XSpace * (i + 1) - ColumsWidth / 2, START_Y + YHeight - (i + 1) * YSpace, START_X + XSpace * (i + 1) + ColumsWidth / 2, YHeight + START_Y, mPaintColumn);
            canvas.drawText(count, ColumsWidth/2+START_X + XSpace * (i + 1) - ColumsWidth / 2, START_Y + YHeight - (i + 1) * YSpace-10, mPaint);
        }
 
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.