自定義view實戰筆記--餅圖demo

1:想要從view的中心開始繪製可以如下

        canvas.save();
        canvas.translate(mWidth / 2, mHeight / 2);
        canvas.restore();

2:數學相關的計算多用:Math類 —三角函數等等

3:想要在一組數據中查找value在這組數據中的位置,可以先排序,再用二分查找法(binarySearch)找出

 int position = Arrays.binarySearch(endAngles, (float) touchDegree);

4:在處理觸摸事件和繪製的時候,特別注意座標問題,可以轉變座標系,常用還可以用兩個變量來提升性能,不用一直繪製 lastTouchedPosition ,currentTouchedPosition

@Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float touchX = event.getX();
                float touchY = event.getY();
                //轉換座標爲圓中心點的座標
                touchX = touchX - mWidth / 2;
                touchY = touchY - mHeight / 2;
                //根據反正切值拿到角度
                touchDegree = MathUtil.getTouchAngle(touchX, touchY);
                Log.e("degree", touchDegree + "");
                //找出觸摸的是第幾塊區域
                float touchRadius = (float) Math.sqrt(touchX * touchX + touchY * touchY);
                if (touchRadius < circleRadius) {
                    int position = Arrays.binarySearch(startAngles, (float) touchDegree);
                    if (position > 0) {
                        currentTouchedPosition = position;
                    } else {
                        // -index - 1 = position
                        currentTouchedPosition = -position - 1;
                    }
                    if (currentTouchedPosition != lastTouchedPosition) {
                        lastTouchedPosition = currentTouchedPosition;
                        Log.e("lastTouchedPosition",lastTouchedPosition +"");
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                lastTouchedPosition = -1;
                invalidate();
                break;
        }
        return true;
    }

5:注意座標系的象限和數學中不一樣

 String percentText = String.format("%.2f", pieBean.getPercent() * 100) + "%";
            if (startAngle % 360 > 90 && startAngle % 360 < 270) {
                mLinePaint.setTextAlign(Paint.Align.RIGHT);
                canvas.drawText(percentText, endX, endY, mLinePaint);
                mLinePaint.setTextAlign(Paint.Align.LEFT);
            } else {
                canvas.drawText(percentText, endX, endY, mLinePaint);
            }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章