kotlin自定义View实现纵向进度条

先来看使用

小效果图如下:

效果图

具体实现:

成员变量部分

var paint:Paint? =null

var rect:RectF? =null

var rectBac:RectF? =null//背景

var progressHeight =0f//进度条高度

var progressWidth =0f//进度条宽度

var rounded =0f//进度条圆角

var colorInt =0//进度条颜色

var background =0//进度条背景色

var progress =0//进度0..100

var textSize =0f//文字大小

var textLocation =1//文字位置 1..3  top..bottom

构造方法

val ta = context.obtainStyledAttributes(attr,R.styleable.VerticalProgress)

progressHeight =ta.getDimension(R.styleable.VerticalProgress_progress_height,100f)

progressWidth =ta.getDimension(R.styleable.VerticalProgress_progress_width,10f)

rounded =ta.getDimension(R.styleable.VerticalProgress_rounded,10f)

textSize =ta.getDimension(R.styleable.VerticalProgress_text_size,16f)

colorInt =ta.getColor(R.styleable.VerticalProgress_color,R.color.black!!)

background =ta.getColor(R.styleable.VerticalProgress_backgroundColor,R.color.black!!)

progress =ta.getInt(R.styleable.VerticalProgress_progress,0)

textLocation =ta.getInt(R.styleable.VerticalProgress_text_location,1)

paint = Paint()

paint!!.color =colorInt

rectBac = RectF(0f,0f,progressWidth +5,progressHeight +5)

rect = RectF(2.5f,2.5f,progressWidth,progressHeight)

onMeasure方法

setMeasuredDimension(rectBac!!.right.toInt(),rectBac!!.bottom.toInt())

绘制过程

paint!!.textSize =textSize

        val fontMetricsInt =paint!!.getFontMetricsInt()

val bounds = Rect()

paint!!.getTextBounds("$progress%",0,"$progress%".length,bounds)

val textHeight =fontMetricsInt.bottom -fontMetricsInt.top

        val textWidth =bounds.right -bounds.left

        val progressFloat =rect!!.bottom - (rect!!.bottom /100f) *progress.toFloat()

rect!!.top =progressFloat +3

//        rect!!.right = if (rect!!.right <= textWidth) textWidth.toFloat() + 10 else rect!!.right

        paint!!.color =background

//        rectBac!!.right =

//            if (rectBac!!.right <= textWidth) textWidth.toFloat() + 15 else rectBac!!.right

        canvas!!.drawRoundRect(rectBac!!,rounded,rounded,paint!!)

//        canvas!!.save()

//        val path = Path()

//        path.addArc(rectBac!!,height.toFloat(),width.toFloat())

//        canvas.clipPath(path)

        paint!!.color =colorInt

        canvas.drawRoundRect(rect!!,rounded,rounded,paint!!)

//        canvas.restore()

        paint!!.color =context.resources.getColor(R.color.white)

when (textLocation) {

    1 -> {

        canvas.drawText("$progress%",width /2f -textWidth /2,10f +textHeight,paint!!)

    }

    2 -> {

        canvas.drawText(

            "$progress%",

            width /2f -textWidth /2,

            rect!!.bottom /2f +textHeight /2,

            paint!!

            )

    }

    3 -> {

        canvas.drawText(

            "$progress%",

            width /2f -textWidth /2,

            rect!!.bottom -10f -textHeight,

            paint!!

            )

        }

}

自定义属性部分

有些小问题,使用的时候就会发现了,没有那么唱的时间搞了,使用者自行解决罢

你可能感兴趣的:(kotlin自定义View实现纵向进度条)