手把手教你畫(huà)餅形圖

項(xiàng)目中需要用到簡(jiǎn)單的餅形圖統(tǒng)計(jì)璃饱,我們就沒(méi)必要去找什么開(kāi)源的,可以嘗試自己畫(huà)一下侈玄。
效果:

餅形圖.jpg

通過(guò)該例子婉刀,你能學(xué)到什么:

  • 對(duì)Paint 深入理解吟温,畫(huà)繪制餅圖序仙,矩形,文字等

  • 加深對(duì)canvas的API的掌握鲁豪,對(duì)自定義View掌握

下面我們分七步來(lái)完成一個(gè)簡(jiǎn)單的餅形圖繪制過(guò)程潘悼。

1. 重新View的構(gòu)造方法
public PieView(Context context) {
        this(context, null);
    }

    public PieView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PieView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPieColorList = new ArrayList<>();
        mPieValue = new ArrayList<>();
        mStringList = new ArrayList<>();
        mPaint = new Paint();
        mMaxString = "";
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(10);//畫(huà)筆寬度
        mPaint.setAntiAlias(true);//抗鋸齒
    }
2.繪制圖形
/**
     * 繪制餅圖
     *
     * @param canvas
     * @param amount
     */
    private void drawPie(Canvas canvas, int amount) {
        mPaint.setColor(mCurrentColor);
        mPaint.setStyle(Paint.Style.FILL);
        int angle = (int) (360f * amount / mMaxValue);
        Log.d("angle", "drawPie: " + angle);
        canvas.drawArc(oval, mStartAngle, angle, true, mPaint);
        mStartAngle += angle;
    }

    /**
     * 繪制矩形
     *
     * @param canvas
     */
    private void drawRect(Canvas canvas) {
        if (mCurrentIndex == 0) {
            rect = new RectF(mRectMarginLeft, mPadding, mRectMarginLeft + RECT_WIDTH, mPadding + RECT_WIDTH);
            canvas.drawRect(rect, mPaint);
        } else {
            rect = new RectF(mRectMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding, mRectMarginLeft + RECT_WIDTH, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + RECT_WIDTH);
            canvas.drawRect(rect, mPaint);
        }
    }

    /**
     * 繪畫(huà)文字
     *
     * @param canvas
     * @param text
     */
    private void drawText(Canvas canvas, String text) {
        mPaint.setColor(TEXT_COLOR);
        if (mCurrentIndex == 0) {
            canvas.drawText(text, mTextMarginLeft, mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
        } else {
            canvas.drawText(text, mTextMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
        }
    }
3.Pie 實(shí)體類
public class Pie {
    public int PieColor;
    public int PieValue;
    public String PieString;

    public Pie(int pieValue, String pieString, int pieColor) {
        this.PieValue = pieValue;
        this.PieString = pieString;
        this.PieColor = pieColor;
    }
}
4.xml引用
    <aikaifa.canvas.widget.PieView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/PieView" />
5.填充數(shù)據(jù)
public class MainActivity extends Activity {
    private ArrayList<Pie> pieArrayList = new ArrayList<>();
    private String[] arr = {"C#", "C", "C++", "JAVA", "JavaScript", "Object-C"};
    private int[] pre = {20, 30, 10, 10, 10, 20};
    private PieView pieView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pieView = (PieView) findViewById(R.id.PieView);
        int[] pieColor = {getResources().getColor(R.color.blue), getResources().getColor(R.color.red), getResources().getColor(R.color.gray_dark),
                getResources().getColor(R.color.dark), getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.black_alpha_light)};
        for (int i = 0; i < arr.length; i++) {
            Pie pie = new Pie(pre[i], arr[i], pieColor[i]);
            pieArrayList.add(pie);
        }
        pieView.SetPie(pieArrayList);
    }
    
}
6.完整的PieView
public class PieView extends View {

    private Paint mPaint;
    //餅圖和矩形的距離
    private final int PIE_RECT_PADDING = getResources().getDimensionPixelSize(R.dimen.pie_rect_padding);
    //矩形的寬度
    private final int RECT_WIDTH = getResources().getDimensionPixelSize(R.dimen.rect_width);
    //矩形和文字的距離
    private final int RECT_TEXT_PADDING = getResources().getDimensionPixelSize(R.dimen.rect_text_padding);
    //文字的大小
    private final int TEXT_SIZE = getResources().getDimensionPixelSize(R.dimen.text_size);
    //文字的垂直距離
    private final int TEXT_VERTICAL_PADDING = getResources().getDimensionPixelSize(R.dimen.text_vertical_padding);
    //得到文字顏色
    private final int TEXT_COLOR = getResources().getColor(R.color.gray_dark);
    //文字和控件頂部的距離
    private float mPadding;
    //餅圖的半徑
    private int mPieRadios;
    //所有數(shù)值的總和
    private int mMaxValue;
    //餅圖開(kāi)始的角度
    private int mStartAngle;
    //文字的寬度
    private int mTextWidth;
    //控件半高
    private int mControlHalfHeight;
    //當(dāng)前索引
    private int mCurrentIndex;
    //左邊距
    private int mRectMarginLeft;
    private int mTextMarginLeft;
    //當(dāng)前顏色
    private int mCurrentColor;
    //圓的范圍
    private RectF oval;
    //最長(zhǎng)的字符串
    private String mMaxString;

    private List<Integer> mPieColorList;
    private List<Integer> mPieValue;
    private List<String> mStringList;
    private ArrayList<Pie> mPieArrayList;

    private RectF rect;

    public PieView(Context context) {
        this(context, null);
    }

    public PieView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PieView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPieColorList = new ArrayList<>();
        mPieValue = new ArrayList<>();
        mStringList = new ArrayList<>();
        mPaint = new Paint();
        mMaxString = "";
        mPaint.setColor(Color.BLACK);
        mPaint.setStrokeWidth(10);//畫(huà)筆寬度
        mPaint.setAntiAlias(true);//抗鋸齒
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        super.onSizeChanged(width, height, oldWidth, oldHeight);
        mTextWidth = (int) mPaint.measureText(mMaxString);
        mControlHalfHeight = height / 2;
        //餅圖半徑
        mPieRadios = mControlHalfHeight - 5;
        //控件內(nèi)容寬度
        int contentWidth = mPieRadios * 2 + PIE_RECT_PADDING + RECT_WIDTH + RECT_TEXT_PADDING + mTextWidth;
        //內(nèi)容的左邊距
        int contentMarginLeft = (width - contentWidth) / 2;
        //矩形的左邊距
        mRectMarginLeft = contentMarginLeft + mPieRadios * 2 + PIE_RECT_PADDING;
        //文字的左邊距
        mTextMarginLeft = mRectMarginLeft + RECT_WIDTH + RECT_TEXT_PADDING;
        //文字和控件頂部的距離
        mPadding = height / mPieArrayList.size() * 0.8f;
        oval = new RectF(contentMarginLeft, mControlHalfHeight - mPieRadios,
                contentMarginLeft + mPieRadios * 2, mControlHalfHeight + mPieRadios);
    }

    /**
     * @param pieArrayList
     */
    public void SetPie(ArrayList<Pie> pieArrayList) {
        mPieArrayList = pieArrayList;
        for (Pie mPie : mPieArrayList) {
            mPieColorList.add(mPie.PieColor);
            mPieValue.add(mPie.PieValue);
            mStringList.add(mPie.PieString);
            if (mMaxString.length() > mPie.PieString.length())
                mMaxString = mPie.PieString;
        }

        //使用postInvalidate可以直接在主線程中更新界面
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mStartAngle = -90;
        mCurrentIndex = 0;
        mMaxValue = 100;
        mPaint.setStyle(Paint.Style.FILL);

        for (int i = 0; i < mPieValue.size(); i++) {
            mCurrentColor = mPieColorList.get(mCurrentIndex);
            Log.i("mCurrentColor", "onDraw: " + mCurrentColor);
            drawPie(canvas, mPieValue.get(mCurrentIndex));
            drawRect(canvas);
            drawText(canvas, mStringList.get(mCurrentIndex));
            mCurrentIndex++;
        }
    }

    /**
     * 繪制餅圖
     *
     * @param canvas
     * @param amount
     */
    private void drawPie(Canvas canvas, int amount) {
        mPaint.setColor(mCurrentColor);
        mPaint.setStyle(Paint.Style.FILL);
        int angle = (int) (360f * amount / mMaxValue);
        Log.d("angle", "drawPie: " + angle);
        canvas.drawArc(oval, mStartAngle, angle, true, mPaint);
        mStartAngle += angle;
    }

    /**
     * 繪制矩形
     *
     * @param canvas
     */
    private void drawRect(Canvas canvas) {
        if (mCurrentIndex == 0) {
            rect = new RectF(mRectMarginLeft, mPadding, mRectMarginLeft + RECT_WIDTH, mPadding + RECT_WIDTH);
            canvas.drawRect(rect, mPaint);
        } else {
            rect = new RectF(mRectMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding, mRectMarginLeft + RECT_WIDTH, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + RECT_WIDTH);
            canvas.drawRect(rect, mPaint);
        }
    }

    /**
     * 繪畫(huà)文字
     *
     * @param canvas
     * @param text
     */
    private void drawText(Canvas canvas, String text) {
        mPaint.setColor(TEXT_COLOR);
        if (mCurrentIndex == 0) {
            canvas.drawText(text, mTextMarginLeft, mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
        } else {
            canvas.drawText(text, mTextMarginLeft, (mCurrentIndex) * TEXT_VERTICAL_PADDING + mPadding + TEXT_SIZE * 0.8f - 5, mPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            float x = event.getX();
            float y = event.getY();
            Log.e("",x+"-----------");
        }
        return  true;
    }
}
7.其他文件

colors.xml

    <color name="dark">#0097a7</color>
    <color name="grey">#e0e0e0</color>
    <color name="gray_dark">#666666</color>
    <color name="black_alpha_light">#3c3f41</color>
    <color name="black_light">#383838</color>
    <color name="blue">#03a9f4</color>
    <color name="red">#ff4081</color>

dimens.xml

    <dimen name="fab_margin">16dp</dimen>
    <dimen name="pie_rect_padding">30dp</dimen>
    <dimen name="rect_text_padding">6dp</dimen>
    <dimen name="rect_width">15dp</dimen>
    <dimen name="text_size">18sp</dimen>
    <dimen name="text_vertical_padding">25dp</dimen>

這樣一個(gè)簡(jiǎn)單的餅形圖繪制就算完成了。
—END

我是洪生鵬爬橡。
熱愛(ài)文學(xué)治唤,熱衷旅行、寫(xiě)作糙申,過(guò)著白天到工地搬磚宾添、晚上寫(xiě)故事的生活。
喜歡我的文章柜裸,記得打賞缕陕、關(guān)注,謝謝疙挺!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末扛邑,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子铐然,更是在濱河造成了極大的恐慌蔬崩,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,639評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件搀暑,死亡現(xiàn)場(chǎng)離奇詭異沥阳,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)自点,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,277評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)桐罕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事冈绊∠丽” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,221評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵死宣,是天一觀的道長(zhǎng)伟恶。 經(jīng)常有香客問(wèn)我,道長(zhǎng)毅该,這世上最難降的妖魔是什么博秫? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,474評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮眶掌,結(jié)果婚禮上挡育,老公的妹妹穿的比我還像新娘。我一直安慰自己朴爬,他們只是感情好即寒,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,570評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著召噩,像睡著了一般母赵。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上具滴,一...
    開(kāi)封第一講書(shū)人閱讀 49,816評(píng)論 1 290
  • 那天凹嘲,我揣著相機(jī)與錄音,去河邊找鬼构韵。 笑死周蹭,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的疲恢。 我是一名探鬼主播凶朗,決...
    沈念sama閱讀 38,957評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼冈闭!你這毒婦竟也來(lái)了俱尼?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,718評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤萎攒,失蹤者是張志新(化名)和其女友劉穎遇八,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體耍休,經(jīng)...
    沈念sama閱讀 44,176評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡刃永,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,511評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了羊精。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片斯够。...
    茶點(diǎn)故事閱讀 38,646評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出读规,到底是詐尸還是另有隱情抓督,我是刑警寧澤,帶...
    沈念sama閱讀 34,322評(píng)論 4 330
  • 正文 年R本政府宣布束亏,位于F島的核電站铃在,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏碍遍。R本人自食惡果不足惜定铜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,934評(píng)論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望怕敬。 院中可真熱鬧揣炕,春花似錦、人聲如沸东跪。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,755評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)越庇。三九已至罩锐,卻和暖如春奉狈,著一層夾襖步出監(jiān)牢的瞬間卤唉,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,987評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工仁期, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留桑驱,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,358評(píng)論 2 360
  • 正文 我出身青樓跛蛋,卻偏偏與公主長(zhǎng)得像熬的,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子赊级,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,514評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容