开发当中,很多地方都需要红点气泡,红点内部显示数量
思路:
1.自定义view,先绘制一个圆形,在绘制一个text文本内容
2.根据view的宽高,取最小值,因为圆形的特点,必须具备正方形区域才能绘制圆形,所以在宽高当中取最小值来绘制圆形
3.内部的text,居中显示,文本的默认显示方法是基于文本的左下角为基点,所以为了让文本居中,要计算偏移量。
4.如何进行偏移呢?
先说X轴,只有知道了文本的宽度,向左偏移一半距离,就可以了
同理,Y轴也是这样的逻辑,向下偏移一半距离,就可以居中了。
val rect = Rect()
//检索文本边界框,保存宽高
paintText.getTextBounds(numberStr, 0, numberStr!!.length, rect)
rect.getWidth()//获取文本的宽度
rect.getHeight()//获取文本的高度
5.全部代码
class RedPoint constructor(
context: Context,
attrs: AttributeSet,
defStyleAttr: Int = 0,
defStyleRes: Int
) :
View(context, attrs, defStyleAttr, defStyleRes) {
constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0, 0)
private val paintBg = Paint()
private val paintText = Paint()
private val textSize =
TypedValue.applyDimension(COMPLEX_UNIT_SP, 14f, context.resources.displayMetrics)
private var numberStr: String? = ""
private var radius: Float = 0f
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
//获取圆点的半径
radius = width.coerceAtMost(height).toFloat() / 2
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
paintBg.color = Color.RED
canvas?.drawCircle(radius, radius, radius, paintBg)
paintText.color = Color.WHITE
paintText.style = Paint.Style.FILL
paintText.textSize = textSize
Log.d(TAG, "textsize:" + paintText.textSize);
val rect = Rect()
//检索文本边界框,保存宽高
paintText.getTextBounds(numberStr, 0, numberStr!!.length, rect)
//绘制文字是以左下角为中心,所以文字要居中,计算偏移量
val x = radius - rect.width() / 2
val y = radius + rect.height() / 2
canvas?.drawText(numberStr!!, x, y, paintText)
}
fun setText(number: String) {
this.numberStr = number
invalidate()
}
private val TAG = "RedPoint"
}