5.自定义view-评分控件RatingBar

1.效果

2.实现原理

1.根据分数分别画选中的星星、正常的星星

2.onTouchEvent 中获取点击、滑动的位置,修改分数,在通过invalidate() 去重新绘制

核心代码:

    @Override
    protected void onDraw(Canvas canvas) {
        int startWidth = mStarFocusBitmap.getWidth();
        for (int i = 0; i < mMarks; i++) {
            int left = getPaddingLeft() + i * startWidth + i * mInterval;
            int top = getPaddingTop();
            if (mCurrentMarks > i) {
                canvas.drawBitmap(mStarFocusBitmap, left, top, null);
            } else {
                canvas.drawBitmap(mStarNormalBitmap, left, top, null);
            }

        }
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX();
                int marks = (int) ((moveX / (mStarFocusBitmap.getWidth() + mInterval)) + 1);
                if (marks != mCurrentMarks) {
                    mCurrentMarks = marks;
                    invalidate();
                }
        }

        return true;
    }

源码地址

posted @ 2020-11-10 17:03  Nixon  阅读(80)  评论(0编辑  收藏  举报