设计Border的颜色、弧度以及宽度
首先在value的styles中添加以下代码
< declare- styleable name= "TextViewBorder" >
< attr name= "borderColor" format= "color" / >
< attr name= "borderRadius" format= "integer" / >
< / declare- styleable>
TextBorderView
package com. demo. widget
import android. annotation. SuppressLint
import android. content. Context
import android. graphics. Canvas
import android. graphics. Paint
import android. graphics. RectF
import android. util. AttributeSet
import android. widget. TextView
import com. demo. flowHistory. R
@SuppressLint ( "AppCompatCustomView" )
class TextBorderView ( context: Context, attrs: AttributeSet? ) :
TextView ( context, attrs ) {
var mStrokeColor = 0
var mFillColor = 0
var mRadius = 0
var mStrokeWidth = 1
var mStyle = Paint. Style. STROKE
private val borderPaint = Paint ( )
private val fillPaint = Paint ( )
@SuppressLint ( "DrawAllocation" )
override fun onDraw ( canvas: Canvas ) {
val w = this . measuredWidth
val h = this . measuredHeight
val r = RectF ( 0 F, 0 F, ( w - 1 ) . toFloat ( ) , ( h - 1 ) . toFloat ( ) )
borderPaint. color = mStrokeColor
borderPaint. strokeWidth = mStrokeWidth. toFloat ( )
borderPaint. style = Paint. Style. STROKE
borderPaint. isAntiAlias = true
canvas. drawRoundRect ( r, mRadius. toFloat ( ) , mRadius. toFloat ( ) , borderPaint)
fillPaint. color = mFillColor
fillPaint. strokeWidth = mStrokeWidth. toFloat ( )
fillPaint. style = Paint. Style. FILL
fillPaint. isAntiAlias = true
canvas. drawRoundRect ( r, mRadius. toFloat ( ) , mRadius. toFloat ( ) , fillPaint)
super . onDraw ( canvas)
}
fun setStrokeColor ( newColor: Int ) {
mStrokeColor = newColor
invalidate ( )
requestLayout ( )
}
fun setFillColor ( newColor: Int ) {
mFillColor = newColor
invalidate ( )
requestLayout ( )
}
fun setViewRadius ( newRadius: Int ) {
mRadius = newRadius
invalidate ( )
requestLayout ( )
}
fun setStrokeWidth ( newWidth: Int ) {
mStrokeWidth = newWidth
invalidate ( )
requestLayout ( )
}
fun setViewStyle ( newStyle: Paint. Style ) {
mStyle = newStyle
invalidate ( )
requestLayout ( )
}
init {
val a = context. theme. obtainStyledAttributes ( attrs,
R . styleable. TextViewBorder, 0 , 0 )
try {
mStrokeColor = a. getInteger ( R . styleable. TextViewBorder_borderColor, 0 )
mRadius = a. getInteger ( R . styleable. TextViewBorder_borderRadius, 0 )
} finally {
a. recycle ( )
}
}
}
使用
import com. demo. widget. TextBorderView
import androidx. core. content. ContextCompat
val tv = TextBorderView ( context, null )
tv. setFillColor ( ContextCompat. getColor ( context, R . color. red) )
tv. setStrokeColor ( ContextCompat. getColor ( context, R . color. black) )
tv. setViewRadius ( 44 )
tv. setStrokeWidth ( 2 )
tv. setPadding ( 30 , 20 , 30 , 20 )