自定义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);
            }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章