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应用描边设置后绘制一遍,就是绘制的文字描边效果。

相关推荐
CYRUS_STUDIO5 小时前
Frida 检测与对抗实战:进程、maps、线程、符号全特征清除
android·逆向
csj507 小时前
安卓基础之《(28)—Service组件》
android
lhbian9 小时前
PHP、C++和C语言对比:哪个更适合你?
android·数据库·spring boot·mysql·kafka
catoop10 小时前
Android 最佳实践、分层架构与全流程解析(2025)
android
ZHANG13HAO10 小时前
Android 13 特权应用(Android Studio 开发)调用 AOSP 隐藏 API 完整教程
android·ide·android studio
田梓燊10 小时前
leetcode 142
android·java·leetcode
angerdream11 小时前
Android手把手编写儿童手机远程监控App之JAVA基础
android
菠萝地亚狂想曲11 小时前
Zephyr_01, environment
android·java·javascript
sTone8737511 小时前
跨端框架通信机制全解析:从 URL Schema 到 JSI 到 Platform Channel
android·前端
sTone8737511 小时前
Java 注解完全指南:从 "这是什么" 到 "自己写一个"
android·前端