淺談Android Canvas繪圖類

android中的繪圖類主要涉及Canvas和Paint兩個類。Canvas相當於畫布,而Paint相當於畫筆。有了畫布和畫筆,就可以進行繪圖了。
要繪圖,首先得調整畫筆,待畫筆調整好之後,再將圖像繪製到畫布上,這樣纔可以顯示在手機屏幕上。Android 中的畫筆是 Paint類,Paint 中包含了很多方法對其屬性進行設置,主要方法如下:

setAntiAlias: 設置畫筆的鋸齒效果。
setColor: 設置畫筆顏色
setARGB: 設置畫筆的a,r,p,g值。
setAlpha: 設置Alpha值
setTextSize: 設置字體尺寸。
setStyle: 設置畫筆風格,空心或者實心。
setStrokeWidth: 設置空心的邊框寬度。
getColor: 得到畫筆的顏色
getAlpha: 得到畫筆的Alpha值。
首先我們舉一個例子來了解一下這些屬性
下面這張圖片是一張圓形進度條 ,那麼我們該怎麼繪製他呢?
這裏寫圖片描述
1.首先準備好3個畫筆Paint類 分別爲

    private Paint mPaintBackground; // 繪製背景圓環的畫筆
    private Paint mPaintProgress; // 繪製背景進度的畫筆
    private Paint mPaintText; // 繪製背景字體的畫筆

另外還有一些圓環的基本屬性

    private int bgColor = Color.WHITE; // 背景圓環的顏色
    private int textColor = Color.CYAN; // 字體的顏色
    private int progressColor = Color.CYAN; // 進度條的顏色
    private float mStrokeWidth = 10;// 背景圓環的寬度
    private float mRadius = 60; // 背景圓環的半徑
    private RectF rectPro;// 進度條的繪製外接矩形
    private int mProgress = 0; // 當前進度
    private int mMaxProgress = 100; // 最大進度

接下來 初始化我們的畫筆

mPaintBackground = new Paint();
        mPaintBackground.setColor(bgColor);
        // 設置抗鋸齒
        mPaintBackground.setAntiAlias(true);
        // 設置防抖動
        mPaintBackground.setDither(true);
        // 設置樣式爲環形
        mPaintBackground.setStyle(Style.STROKE);
        // 設置環形的寬度
        mPaintBackground.setStrokeWidth(mStrokeWidth);

        mPaintProgress = new Paint();
        mPaintProgress.setColor(progressColor);
        // 設置抗鋸齒
        mPaintProgress.setAntiAlias(true);
        // 設置防抖動
        mPaintProgress.setDither(true);
        // 設置樣式爲環形
        mPaintProgress.setStyle(Style.STROKE);
        // 設置環形的寬度
        mPaintProgress.setStrokeWidth(mStrokeWidth);

        mPaintText = new Paint();
        mPaintText.setColor(textColor);
        // 設置抗鋸齒
        mPaintText.setAntiAlias(true);
        mPaintText.setTextAlign(Align.CENTER);
        mPaintText.setTextSize(40);

畫筆的準備工作已經做完了,接下來我們使用Canvas畫布對象。
下圖中列舉了API中Canvas繪圖的各種方法。
這裏寫圖片描述
繪製上圖中的進度條 我們需要用到drawCircle方法繪製圓;drawArc繪製圓弧;drawText方法繪製字體。

@Override
    protected void onDraw(Canvas canvas) {
        float angle = mProgress / (mMaxProgress * 1.0f) * 360; // 圓弧角度
        initRect();
        //繪製背景圓環
        canvas.drawCircle(mWidth / 2, mHeight / 2, mRadius,
                mPaintBackground);
        //繪製進度條
        canvas.drawArc(rectPro, -90, angle, false, mPaintProgress);
        //繪製字體
        canvas.drawText(mProgress + "%", mWidth / 2, mHeight / 2, mPaintText);
        if (mProgress < mMaxProgress) {
            mProgress += 2;
            invalidate();
        }

最終效果圖爲:
這裏寫圖片描述
想知道關於繪製上圖中自定義的環形進度條的詳細實現,請轉到
http://blog.csdn.net/a253664942/article/details/45115407

發佈了61 篇原創文章 · 獲贊 14 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章