Android控制条 Android自定义控制条效果
rains at night 人气:0ControlBar
自定义一个可以调节大小的控件,可以根据宽高来指定控制条方向。当width >= heigth时,为横向控制条,否则为竖向控制条
onMeasure
根据用户给定的width与height计算控制条的坐标。
1.主要的计算思路
先计算横向的的坐标点,竖向的坐标点即横向的逆时针旋转90度再向下移一个heigth的长度。
//横向坐标点 mHorLArcFirstPathX = mRadius + mLArcLength; mHorLArcFirstPathY = startY + mBarHeight * (1.0f - LITTLE_ARC_PER_WIDTH) / 2.0f ; //对应竖向坐标点 mLArcFirstPathX = mHorLArcFirstPathY; mLArcFirstPathY = -mHorLArcFirstPathX + longSide;
onDraw
根据计算所得坐标点,构建路径,绘图
super.onDraw(canvas); mBgPaint.setColor(Color.WHITE); canvas.drawPath(mBgPath, mBgPaint); mBgPaint.setColor(Color.GRAY); canvas.drawPath(mMaxPath, mBgPaint); canvas.drawPath(mPath, mPaint); mBgPaint.setColor(Color.WHITE); if(mDirection == HORIZONTAL){ canvas.drawCircle(mRadius + mPercent * mBarWidth, mRadius, mRadius, mBgPaint); canvas.drawCircle(mRadius + mPercent * mBarWidth, mRadius, mRadius - SPACING, mPaint); }else { canvas.drawCircle(mRadius, mHeight - (mRadius + mPercent * mBarWidth), mRadius, mBgPaint); canvas.drawCircle(mRadius, mHeight - (mRadius + mPercent * mBarWidth), mRadius - SPACING, mPaint); }
onTouchEvent
根据手指滑动,动态调整数值大小
@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: float distance = 0; float maxDist = 0; switch (mDirection){ case HORIZONTAL: distance = event.getX(); maxDist = mWidth; break; case VERTICAL: distance = mHeight - event.getY(); maxDist = mHeight; break; } if(distance <= mRadius){ updateView(MIN_VALUE); }else if(distance >= maxDist - mRadius){ updateView(MAX_VALUE); }else { updateView(calculatingValue(distance)); } return true; default: return super.onTouchEvent(event); } }
实际效果如图所示
横向控制条
竖向控制条
项目github地址
加载全部内容