android 绘制斜体文本的一种方式

直接给 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();
相关推荐
阿巴斯甜14 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker14 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952715 小时前
Andorid Google 登录接入文档
android
黄林晴16 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android