自定義View之kotlin繪製手勢設定溫度控制元件

villa_mou7發表於2018-08-02

引言

最近公司接了一個車聯網的專案,主要是新能源汽車的一些控制功能,其中涉及到一個是溫度的調節功能,產品的意思是做一個手勢滑動調節溫度,大概意思我是明白的。就是要手勢調節唄,沒辦法,誰讓我是搬磚的呢,人為刀俎,我為魚肉,只有搞了; 最後搞出來的效果大概如下,不過還沒確定,  

自定義View之kotlin繪製手勢設定溫度控制元件

思路

在這裡我先說下自己的實現思路,這個控制元件的難點主要是手勢控制,其他的都很簡單,沒有什麼好說的,控制的一些具體的數值我是寫死的,沒有做自定義擴充,主要是閒麻煩,如果有需要可以自己的實現;

具體的實現步奏

  • 首先繪製圓盤,刻度,陰影(需要關閉硬體加速),文字
  • 然後根據劃過的角度繪製進度條
  • 最後根絕touch事件重新繪製,並設定資料回撥

程式碼實現

1,繪製前的準備

首先kotlin提供了init方法,我們需要在這個方法裡面初始化我們需要的畫筆和一些資料 注:這裡涉及到陰影的繪製,所以必須關閉硬體加速

 init {
        //關閉硬體加速
        setLayerType(View.LAYER_TYPE_SOFTWARE, null)

        mInCirclePaint.color = Color.WHITE
        mInCirclePaint.strokeWidth = 1f
        mInCirclePaint.style = Paint.Style.FILL
        mInCirclePaint.setShadowLayer(25f, 0f, 0f, Color.GRAY)


        mGrayLinePaint.color = Color.parseColor("#00EEEE")
        mGrayLinePaint.strokeWidth = dp2px(1f).toFloat()
        mGrayLinePaint.style = Paint.Style.STROKE
        mGrayLinePaint.setShadowLayer(15f, 0f, 0f, Color.GRAY)

        mTempTextPaint.textSize = sp2px(32f).toFloat()
        mTempTextPaint.style = Paint.Style.FILL
        mTempTextPaint.color = Color.parseColor("#7CCD7C")
        mTempTextPaint.textAlign = Paint.Align.CENTER
        mTempTextPaint.isFakeBoldText = true
        mTempTextPaint.setShadowLayer(5f, 0f, 0f, Color.GRAY)

        mTextPaint.textSize = sp2px(18f).toFloat()
        mTextPaint.style = Paint.Style.FILL
        mTextPaint.color = Color.parseColor("#aaaaaa")
        mTextPaint.textAlign = Paint.Align.CENTER
//        mTextPaint.setShadowLayer(5f, 0f, 0f, Color.GRAY)

        mLineProgressPaint.style = Paint.Style.STROKE
        mLineProgressPaint.strokeWidth = dp2px(10f).toFloat()
        mLineProgressPaint.color = Color.parseColor("#7CCD7C")
//        mLineProgressPaint.setShadowLayer(5f, 0f, 0f, Color.GRAY)

        mProgressCirclePaint.style = Paint.Style.FILL
//        mProgressCirclePaint.setShadowLayer(15f, 0f, 0f, Color.GRAY)

        mProgressPaint.style = Paint.Style.FILL
        mProgressPaint.color = Color.parseColor("#436EEE")
        mProgressPaint.strokeCap = Paint.Cap.ROUND
//        mProgressPaint.setShadowLayer(5f, 0f, 0f, Color.GRAY)

        mPaintTriangle.style = Paint.Style.FILL
        mPaintTriangle.color = Color.parseColor("#436EEE")

    }
複製程式碼

然後我們需要重寫onMeasure()方法,因為這個控制元件必須是正方形的,所以我們必須保證寬和高一致;

 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = View.MeasureSpec.getSize(widthMeasureSpec)
        val height = View.MeasureSpec.getSize(heightMeasureSpec)
        val imageSize = if (width < height) width else height
        setMeasuredDimension(imageSize, imageSize)
    }
複製程式碼

再之後我們需要知道一些具體的寬高值,從而設定半徑的大小,一般是在onSizeChanged()方法裡面拿到

   override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mHeight = Math.min(h, w)
        mWidth = height
        dialRadius = (width / 2 - dp2px(10f))
        arcRadius = dialRadius / 2
        mBgRectf = RectF(-dialRadius * 1f / 2 - dp2px(5f), -dialRadius * 1f / 2 - dp2px(5f), dialRadius * 1f / 2 + dp2px(5f), dialRadius * 1f / 2 + dp2px(5f))
    }
複製程式碼

2,繪製

接下來就開始繪製檢視了,繪製之前需要把檢視的原心移動到中心位置

 canvas.translate(mWidth * 1f / 2, mHeight * 1f / 2);
複製程式碼

接著就開始繪製,首先我們繪製最外邊源的線,這裡繪製180根線,其中30根長線

    private var beginAngle = 0f
    private val drawLine = { canvas: Canvas ->
        beginAngle = 0f
        canvas.save()
        for (i in 0..180) {
            canvas.save()
            canvas.rotate(beginAngle)
            mGrayLinePaint.setARGB(180, (0.7 * i * 2).toInt(), ((255 - 0.7 * i * 2).toInt()), ((255 - 0.7 * i * 2).toInt()))
            if (beginAngle % 12 == 0f) {
                canvas.drawLine(dialRadius * 7f / 9 - dp2px(5f), 0f, dialRadius * 8f / 9, 0f, mGrayLinePaint)
            } else {
                canvas.drawLine(dialRadius * 7f / 9, 0f, dialRadius * 8f / 9, 0f, mGrayLinePaint)
            }
            beginAngle += 2f
            canvas.restore()
        }
        canvas.restore()
    }
複製程式碼

效果如下  

自定義View之kotlin繪製手勢設定溫度控制元件

接著開始繪製中心的文字,如果如下

    private val drawText = { canvas: Canvas ->
        val baseLineY = Math.abs(mTempTextPaint.ascent() + mTempTextPaint.descent()) / 2
        mTempTextPaint.setARGB(180, (0.7 * currentAngle).toInt(), (255 - 0.7 * currentAngle).toInt(), (255 - 0.7 * currentAngle).toInt())
        if (temText == 30 || temText == 29) {
            mTempTextPaint.setARGB(255, 255, 0, 0)
        } else if (temText == 15) {
            mTempTextPaint.setARGB(255, 0, 255, 255)
        }
        canvas.drawText("${temText}°", 0f, baseLineY + dp2px(20f), mTempTextPaint)
        canvas.drawText("最大溫度設定", 0f, baseLineY - dp2px(20f), mTextPaint)
    }
複製程式碼

自定義View之kotlin繪製手勢設定溫度控制元件

接下來就開始繪製進度條和陰影部分

 private val drawPointCircle = { canvas: Canvas ->
        canvas.save()
        canvas.rotate(rotateAngle + 2)
        mProgressPaint.setARGB(255, (0.7 * currentAngle).toInt(), (260 - 0.7 * currentAngle).toInt(), (260 - 0.7 * currentAngle).toInt())
        mPaintTriangle.setARGB(255, (0.7 * currentAngle).toInt(), (260 - 0.7 * currentAngle).toInt(), (260 - 0.7 * currentAngle).toInt())
        if (temText == 30 || temText == 29) {
            mProgressPaint.setARGB(255, 255, 0, 0)
            mPaintTriangle.setARGB(255, 255, 0, 0)
        } else if (temText == 15) {
            mProgressPaint.setARGB(255, 0, 255, 255)
            mPaintTriangle.setARGB(255, 0, 255, 255)
        }
        val path = Path()
        path.moveTo(dialRadius * 1f / 2 + dp2px(5f), (-dp2px(10f)).toFloat())
        path.lineTo(dialRadius * 1f / 2 + dp2px(5f), dp2px(10f).toFloat())
        path.lineTo(dialRadius * 1f / 2 - dp2px(10f), 0f)
        path.close()
        canvas.drawPath(path, mPaintTriangle)
        val point = dialRadius * 1f / 2 + dp2px(5f)
        canvas.drawCircle(point, 0f, dp2px(10f).toFloat(), mProgressPaint)
        canvas.restore()
    }

    private val drawProgress = { canvas: Canvas ->
        if (rotateAngle > 0) {
            mProgressCirclePaint.color = Color.parseColor("#00ffff")
            canvas.drawCircle(dialRadius * 1f / 2 + dp2px(5f), 0f, dp2px(5f).toFloat(), mProgressCirclePaint)
        }
        val colors = intArrayOf(Color.parseColor("#00ffff"), Color.parseColor("#ff0000"))
        val mShader = SweepGradient(0f, 0f, colors, null)
        mLineProgressPaint.shader = mShader
        canvas.drawArc(mBgRectf, 0f, rotateAngle, false, mLineProgressPaint)
    }
複製程式碼

自定義View之kotlin繪製手勢設定溫度控制元件

2,手勢

繪製檢視結束,現在開始手勢的處理,主要就是處理touch事件,我們以圓心為座標圓點,建立座標系,求出(targetX, targetY)座標與x軸的夾角,顯現程式碼如下

private val calcAngle = { targetX: Float, targetY: Float ->
        val x = targetX - width / 2
        val y = targetY - height / 2
        val radian: Double

        if (x != 0f) {
            val tan = Math.abs(y / x)
            if (x > 0) {
                if (y >= 0) {
                    radian = Math.atan(tan.toDouble())
                } else {
                    radian = 2 * Math.PI - Math.atan(tan.toDouble())
                }
            } else {
                if (y >= 0) {
                    radian = Math.PI - Math.atan(tan.toDouble())
                } else {
                    radian = Math.PI + Math.atan(tan.toDouble())
                }
            }
        } else {
            if (y > 0) {
                radian = Math.PI / 2
            } else {
                radian = -Math.PI / 2
            }
        }
        (radian * 180 / Math.PI).toFloat()
    }
複製程式碼

然後在touch事件中進行處理,主要程式碼如下

override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                isDown = true
                downX = event.x
                downY = event.y
                currentAngle = calcAngle(downX, downY)
            }

            MotionEvent.ACTION_MOVE -> {
                isMove = true
                val targetX: Float = event.x
                val targetY: Float = event.y
                val angle = calcAngle(targetX, targetY)
                // 滑過的角度增量
                var angleIncreased = angle - currentAngle
                if (angleIncreased < -180) {
                    angleIncreased += 360
                } else if (angleIncreased > 180) {
                    angleIncreased -= 360
                }
                increaseAngle(angleIncreased)
                currentAngle = angle
                invalidate()
                // 滑過的角度增量
            }

            MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                if (isDown) {
                    if (isMove) {
                        temparetureChangeListner?.invoke(temText)
                        isMove = false
                    }
                    isDown = false
                }
            }

        }
        return true
    }
複製程式碼

計算出當前角度對應的溫度值

    /**
     * 增加旋轉角度
     */
    private val increaseAngle = { angle: Float ->
        rotateAngle += angle
        if (rotateAngle < 0) {
            rotateAngle = 0f
        } else if (rotateAngle > 360f) {
            rotateAngle = 360f
        }
        temText = (rotateAngle / 360 * 15).toInt() + 15
    }

複製程式碼

這樣一個溫度控制元件就做好了,喜歡的話麻煩點個贊哦 專案也傳到了github,有興趣可以去下載玩一下 github專案地址

如果喜歡請關注我的公眾號,時時分享技術乾貨,公眾號二維碼如下:

自定義View之kotlin繪製手勢設定溫度控制元件

相關文章