class MandarinTextView(context: Context, attrs: AttributeSet?) :
AppCompatTextView(context, attrs) {
//外框线
private var mLinePaint: Paint = Paint()
//内十字线
private var mDottedLinePaint: Paint = Paint()
//田字格区域
private var r2: RectF = RectF()
//外框颜色
private var outlineColor: Int
//内框颜色
private var inlineColor: Int
//外框宽度
private var outlineWidth: Int
//内框宽度
private var inlineWidth: Int
//外框圆度
private var borderRadius: Int
//内框透明度
private var inlineAlpha: Float
init {
// 获取参数
val ta = context.obtainStyledAttributes(
attrs,
R.styleable.MandarinTextView
)
outlineColor = ta.getColor(
R.styleable.MandarinTextView_outlineColor,
Color.parseColor("#666666")
)
inlineColor = ta.getColor(
R.styleable.MandarinTextView_inlineColor,
Color.parseColor("#DDDDDD")
)
outlineWidth = ta.getDimensionPixelSize(
R.styleable.MandarinTextView_outlineWidth,
0.5f.px.toInt()
)
inlineWidth = ta.getDimensionPixelSize(
R.styleable.MandarinTextView_inlineWidth,
0.5f.px.toInt()
)
borderRadius = ta.getDimensionPixelSize(
R.styleable.MandarinTextView_outlineRadius,
5f.px.toInt()
)
inlineAlpha = ta.getFloat(
R.styleable.MandarinTextView_inlineAlpha,
0.8f
)
// 释放资源
ta.recycle()
mLinePaint.color = outlineColor
mLinePaint.style = Paint.Style.STROKE
mLinePaint.strokeWidth = outlineWidth.toFloat()
mLinePaint.isAntiAlias = true
mLinePaint.pathEffect = DashPathEffect(floatArrayOf(15f, 10f), 0f)
mDottedLinePaint.color = inlineColor
mDottedLinePaint.style = Paint.Style.STROKE
mDottedLinePaint.strokeWidth = inlineWidth.toFloat()
mDottedLinePaint.isAntiAlias = true
mDottedLinePaint.alpha = (255 * inlineAlpha).toInt()
mDottedLinePaint.pathEffect = DashPathEffect(floatArrayOf(15f, 10f), 0f)
}
override fun onDraw(canvas: Canvas) {
canvas.drawLine(width / 2f, 0f, width / 2f, height.toFloat(), mDottedLinePaint)
canvas.drawLine(0f, height / 2f, width.toFloat(), height / 2f, mDottedLinePaint)
r2.set(
0f + outlineWidth / 2,
0f + outlineWidth / 2,
width.toFloat() - outlineWidth / 2,
height.toFloat() - outlineWidth / 2
)
canvas.drawRoundRect(r2, borderRadius.toFloat(), borderRadius.toFloat(), mLinePaint)
super.onDraw(canvas)
}
fun setOutlineColor(color: Int) {
outlineColor = color
mLinePaint.color = outlineColor
invalidate()
}
}
网友评论