Android开发 双向进度条自定义View____TwoWayProgressView
作者:互联网
前言
一个双向进度的自定义View,已经封装好,可以直接使用
效果图
代码
import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import androidx.annotation.ColorInt /** * 双向进度View */ class TwoWayProgressView(context: Context?, attrs: AttributeSet?) : View(context, attrs) { private var mWidth = 0 private var mHeight = 0 private var mCurrentProgress = 100 private var mPaint: Paint = Paint() private var mIsRound = true private var mStartColor = Color.parseColor("#48F3D0") private var mEndColor = Color.parseColor("#1DBBFF") private var mIsHorizontal = false init { mPaint.style = Paint.Style.FILL mPaint.isAntiAlias = true } /** * 是否是圆角 */ fun isRound(isRound: Boolean) { mIsRound = isRound invalidate() } /** * 设置颜色渐变 * [orientation]渐变方向 true=横向 false=竖向 * [startColor] 开始颜色 * [endColor] 结束颜色 */ fun setLinearGradientColor(isHorizontal: Boolean, @ColorInt startColor: Int, @ColorInt endColor: Int) { mIsHorizontal = isHorizontal mStartColor = startColor mEndColor = endColor invalidate() } /** * 设置进度 0-100 */ fun setProgress(progress: Int) { mCurrentProgress = progress invalidate() } fun getProgress() = mCurrentProgress /** * 测量尺寸 */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) mWidth = MeasureSpec.getSize(widthMeasureSpec) mHeight = MeasureSpec.getSize(heightMeasureSpec) setMeasuredDimension(mWidth, mHeight) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) drawProgress(canvas) } fun drawProgress(canvas: Canvas) { val linearGradient = if (mIsHorizontal) { //从左到右 LinearGradient(0f, 0f, mWidth.toFloat(), 0f, mStartColor, mEndColor, Shader.TileMode.CLAMP) } else { //从上到下渐变 LinearGradient(0f, 0f, 0f, mHeight.toFloat(), mStartColor, mEndColor, Shader.TileMode.CLAMP) } mPaint.shader = linearGradient val widthScale = (mWidth.toFloat() / 2) / 100 val left = mWidth / 2 - widthScale * mCurrentProgress val right = mWidth / 2 + widthScale * mCurrentProgress val rect = RectF() rect.top = 0f rect.left = left rect.right = right rect.bottom = mHeight.toFloat() if (mIsRound) { canvas.drawRoundRect(rect, mWidth / 2f, mWidth / 2f, mPaint) } else { canvas.drawRect(rect, mPaint) } } }
标签:mWidth,自定义,进度条,private,fun,TwoWayProgressView,0f,var,rect 来源: https://www.cnblogs.com/guanxinjing/p/16470722.html