package com.cheng.blzb.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatTextView


class StrokeTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
    private val outlineTextView = AppCompatTextView(context, attrs, defStyleAttr)

    init {
        initView()
    }

    private fun initView() {
        val paint = outlineTextView.paint
        paint.strokeWidth = 3f //描边宽度

        paint.style = Paint.Style.STROKE
        outlineTextView.setTextColor(Color.WHITE) //描边颜色
        outlineTextView.setGravity(gravity)
    }

    override fun setLayoutParams(params: ViewGroup.LayoutParams?) {
        super.setLayoutParams(params)
        outlineTextView.setLayoutParams(params)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        //设置轮廓文字
        val outlineText = outlineTextView.getText()
        if (outlineText == null || outlineText != getText()) {
            outlineTextView.text = getText()
            postInvalidate()
        }
        outlineTextView.measure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        outlineTextView.layout(left, top, right, bottom)
    }

    override fun onDraw(canvas: Canvas) {
        outlineTextView.typeface = typeface
        outlineTextView.draw(canvas)
        super.onDraw(canvas)
    }

    fun setStrokeColor(@ColorInt color: Int) {
        outlineTextView.setTextColor(color)
        postInvalidate()
    }

    fun setStrokeWidth(width: Float) {
        outlineTextView.paint.strokeWidth = width
        postInvalidate()
    }
}