自定义View 笑脸评分(kotlin语言)

自定义View 笑脸评分(kotlin语言)

效果

自定义View 笑脸评分(kotlin语言)_第1张图片

class MyView (context: Context,attributeSet: AttributeSet) : View(context,attributeSet) {
    var picw : Int =0
    var picy : Int =0
    var flag : Boolean = false
    var x : Float? = 0.0f
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val paint = Paint()
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.zero)//零分笑脸
         val full = BitmapFactory.decodeResource(resources, R.mipmap.full)//满分笑脸
        val half = BitmapFactory.decodeResource(resources, R.mipmap.half)//半分笑脸
        val width = bitmap.width;
        val height = bitmap.height
        picw=width
        picy=height
        for (i in 0..4){
            canvas!!.drawBitmap(bitmap,i*width.toFloat(),10.0f,paint)
        }
        val count = x!!.toInt() / picw
        val halfcount = x!! / picw
        val bigDecimal = BigDecimal(halfcount.toDouble())
        val toDouble = bigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP).toDouble()
        val split = toDouble.toString().split(".")
        if (flag){
            for (i in 0..count-1){
                canvas!!.drawBitmap(full,i*width.toFloat(),10.0f,paint)
            }
            if (split[1].toInt()>=5){
                canvas!!.drawBitmap(half,count*width.toFloat(),10.0f,paint)
            }
        }
    }
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        x= event!!.getX()
        flag = true
        postInvalidate()
        return true
    }
}

你可能感兴趣的:(安卓)