drawText() 绘制文字
绘制进度条:paint.strokeCap = Paint.CAP.RONUD 线条两边样式
设置文字字体:paint.typeFace = Resources.Compat.getFont(context,font)
设置加粗 paint.isFakeBoldText
设置居中: paint.setTextAlign = Paint.Align.CENTER //居中, 并不是真正的居中 往往会比较靠上,有baseLine 基线的作用, baseLine 有五条 ,(ascent,top,desencent,bottom)会有纵向 | 便宜
通过getTextBounds(text,start,end,bounds //存放结果 ) 获得left ,top right bottom 偏移量
静态文字设置示例:
paint.getTextBounds("AAAA",0,"AAAA".length,bounds) canvas.drawText("AAAA",width / 2f,height / 2f - ((bounds.top + bounds.bottom) / 2),paint)
计算偏移量 设置居中,
动态设置:
paint.getFontMetrics(fontMetrices) canvas.drawText("abcpst",width / 2f,height / 2f - ((fontMetrices.ascent + fontMetrices.descent) / 2),paint)
文字靠左显示:
paint.textAlign = Paint.Align.LEFT canvas.drawText("ababab",0f, - fontMetrices.top,paint)
靠左上角
paint.textAlign = Paint.Align.LEFT paint.getTextBounds("ababab",0,"ababab".length,bounds) canvas.drawText("ababab",0f, - bounds.top.toFloat(),paint) //静态
文字左右各占空间 字体越大 占用空越大 示例:
paint.textSize = 150.dppaint.textAlign = Paint.Align.LEFTpaint.getTextBounds("ababab",0,"ababab".length,bounds)canvas.drawText("ababab",0f, - bounds.top.toFloat(),paint) paint.textSize = 15.dppaint.getTextBounds("ababab",0,"ababab".length,bounds)canvas.drawText("ababab",0f, - bounds.top.toFloat(),paint)
字体越大 文字间间距越大,因为有baseLine的左右以及textBound设置
解决:
paint.textSize = 150.dppaint.textAlign = Paint.Align.LEFTpaint.getTextBounds("ababab",0,"ababab".length,bounds)canvas.drawText("ababab",- bounds.left.toFloat(), - bounds.top.toFloat(),paint) paint.textSize = 15.dppaint.getTextBounds("ababab",0,"ababab".length,bounds)canvas.drawText("ababab",-bounds.left.toFloat(), - bounds.top.toFloat(),paint)
其实仔细看还是有一点点间距,这是文字的字体所占用的缝隙
StaticLayout 使用
StaticLayout(text,textPaint,width ,align,span 间距,行距)
val staticLayout = StaticLayout.Builder.obtain(text, 0, text.length, textPaint, width) textPaint.textSize = 16.dp staticLayout.build().draw(canvas)
paint.fontSpacing 行间距
单个图文混合排序示例
canvas.drawBitmap(bitmap, width - IMAGE_SIZE, IMAGEPADDING, paint)paint.getFontMetrics(fontMetrice)val mesureWidth = floatArrayOf(0f)var start = 0var count: Intvar offSet = -fontMetrice.topvar maxWidth: Floatwhile (start < text.length) {if (offSet + fontMetrice.bottom < IMAGEPADDING || offSet + fontMetrice.top > IMAGE_SIZE + IMAGEPADDING) {maxWidth = width.toFloat()} else {maxWidth = width.toFloat() - IMAGE_SIZE}count = paint.breakText(text,start,text.length,true,maxWidth,mesureWidth)canvas.drawText(text, start, start + count, 0f, offSet, paint)start += countoffSet += paint.fontSpacing}