绘制文字

获取文字的相关属性:

1.Paint.FontMetrics()

用法

private val paint = Paint().apply {
    isAntiAlias = true
    textSize = 120.dp
    style = Paint.Style.FILL
}
private val fontMetrics = Paint.FontMetrics()

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    paint.getFontMetrics(fontMetrics)
    canvas.drawText("qwer", 0f, -fontMetrics.ascent, paint)
    println("descent ${fontMetrics.descent} ascent ${fontMetrics.ascent} top ${fontMetrics.top} bottom ${fontMetrics.bottom}")
}

输出结果

System.out: descent 87.890625 ascent -333.98438 top -380.21484 bottom 97.55859

效果图

关于绘制文字的5条线

ascent: 系统建议的,绘制单个字符时,字符应当的最高高度所在线
descent:系统建议的,绘制单个字符时,字符应当的最低高度所在线
top: 可绘制的最高高度所在线
bottom: 可绘制的最低高度所在线

可以看到用fontMetrics这种方法是贴不了顶的,因为descent,ascent,top,bottom并不是文字真实的绘制区域
那么要贴顶的话就要第二种测量方法了

2.paint.getTextBounds

用法

private val bounds = Rect()
private val paint = Paint().apply {
    isAntiAlias = true
    textSize = 120.dp
    style = Paint.Style.FILL
}

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    paint.getTextBounds("qwer", 0, "qwer".length, bounds)
    println("top ${bounds.top} bottom ${bounds.bottom} left ${bounds.left} right ${bounds.right}")
    canvas.drawText("qwer", 0f, (-bounds.top).toFloat(), paint)
}

输出结果

System.out: top -197 bottom 74 left 11 right 786

效果图

贴顶了,bounds的4个值是真实绘制的区域

注意:以上纯属记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值