直接给 TextPaint设置斜体 然后通过 StaticLayout绘制也可以绘制斜体。但是问题是 StaticLayout直接绘制有时候文本会被裁切,也就是绘制范围没法精准控制。
js
Rect bounds = new Rect();
mTextPaint.getTextBounds(c,0,c.length(),bounds);
canvas.save();
canvas.translate(bounds.width()/2f, bounds.height()/2f); // 移动到你想要的中心点
canvas.skew(-0.3f, 0); // 倾斜
canvas.translate(-bounds.width()/2f, -bounds.height()/2f); // 移回原位置
StaticLayout itemStaticLayout = new StaticLayout(c, mTextPaint, txtWidth,
Layout.Alignment.ALIGN_NORMAL, 1.0F, 0, false);
itemStaticLayout.draw(canvas);
canvas.restore();
计算文本倾斜之后的宽度
js
float skewX = 0.3f;
float w = paint.measureText(text);
float h = bounds.height();
float skewWidth = w + h * Math.abs(skewX);
// 让文字居中显示(考虑倾斜后的宽度)
float startX = (canvasWidth - skewWidth) / 2;
canvas.save();
canvas.translate(pivotX, pivotY);
canvas.skew(skewX, 0);
canvas.translate(-pivotX, -pivotY);
canvas.drawText(text, startX, baselineY, paint);
canvas.restore();