版权声明
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/16470722.html
前言
一个双向进度的自定义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) } } }
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/16470722.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-07-12 Android开发 VideoView视频播放详解