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();
相关推荐
_李小白5 小时前
【android opencv学习笔记】Day 28: 滤波算法之中值滤波器
android·opencv·学习
代龙涛7 小时前
WordPress page.php 页面模板与自定义模板使用方法
android·开发语言·php
爱莉希雅&&&8 小时前
zabbix快速搭建和使用
android·linux·数据库·zabbix·监控
zfoo-framework10 小时前
理解kotlin limitedParallelism(1)与Actor模型
android·开发语言·kotlin
2401_8657213311 小时前
御网杯初赛2026
android
葱段12 小时前
【Compose】输入框(TextField)点击空白处失焦并关闭软键盘
android
刮风那天14 小时前
Android Framework 核心架构图
android
__Witheart__14 小时前
3588 安卓编译空间不足报错
android
aaajj14 小时前
【Android】手机屏幕劫持防护
android·智能手机
写做四月一日的四月一日15 小时前
在安卓手机上安装小龙虾openclaw并配置QQ机器人接入
android·人工智能