Android 自定义TextView实现文字描边效果

效果如下

自定义两个属性

复制代码
//attrs.xml
<!-- 文本描边颜色 -->
<attr name="strokeTextColor" format="reference|color" />
<!-- 文本描边粗细 -->
<attr name="strokeTextWidth" format="reference|integer" />

实现类

java 复制代码
public class StrokeTextView extends androidx.appcompat.widget.AppCompatTextView {
    private static final int[] STROKE_ATTRS = new int[]{R.attr.strokeTextColor, R.attr.strokeTextWidth};
    private @ColorInt int strokeColor = 0;
    private int strokeWidth = 3;

    public StrokeTextView(Context context) {
        this(context, null);
    }

    public StrokeTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public StrokeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, STROKE_ATTRS, defStyleAttr, 0);
        strokeColor = typedArray.getColor(0, 0);
        strokeWidth = typedArray.getInt(1, 3);
        typedArray.recycle();
    }

    public void setStrokeColor(@ColorInt int color) {
        strokeColor = color;
        invalidate();
    }

    public void setStrokeWidth(int width) {
        strokeWidth = width;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint wkPaint = getLayout().getPaint();
        int preColor = wkPaint.getColor();
        Paint.Style prePaintStyle = wkPaint.getStyle();
        // apply stroke paint
        wkPaint.setColor(strokeColor);
        wkPaint.setStrokeWidth(strokeWidth);
        wkPaint.setStyle(Paint.Style.STROKE);
        // draw text outline
        getLayout().draw(canvas);

        // restore paint
        wkPaint.setColor(preColor);
        wkPaint.setStrokeWidth(0);
        wkPaint.setStyle(prePaintStyle);
        super.onDraw(canvas);
    }

}

在onDraw方法中,拿到负责绘制文本的Layout对象,对其Paint应用描边设置后绘制一遍,就是绘制的文字描边效果。

相关推荐
ZHOUPUYU1 小时前
PHP 现代工程实践:从语言特性到高性能 Web 应用构建
android·前端·php
treasure1403 小时前
Flutter低级教程(2027年1月重制版)
android·flutter·ios·gui·web·dart·移动端
艾派森3 小时前
Python帕累托分析实战:用二八法则找出贡献80%营收的核心商品
android·开发语言·python
橙光成长4 小时前
GameScrcpy:不装模拟器,用键鼠手柄和 TypeScript 脚本接管你的安卓手游
android·javascript·typescript·开源·1024程序员节
ZHOUPUYU5 小时前
PHP 实战:从零构建一个高可用的小型 Web 应用
android·前端·php
程序猿追6 小时前
返库看板最小化后还会刷新吗?HarmonyOS 7 窗口状态实测
android·开发语言·kotlin·harmonyos
奶龙无翅何谈飞6 小时前
从手机输入到 Windows 进程退出码,拆解 Code Link 的远程终端链路
android·windows·adb·蓝牙·开发工具
xixiaoyunya6 小时前
MySQL 单表备份:从手动导出到定时自动化的完整实践
android·mysql·自动化
2501_915921436 小时前
iOS 上架 App Store 常见 ITMS 报错排查,哪些需要修改哪些是警告
android·ios·小程序·https·uni-app·iphone·webview
默 语7 小时前
【HarmonyOS7】ArkTS通用属性实战(一):一文吃透尺寸设置 width/height/size
android