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

相关推荐
mmsx32 分钟前
Android 手簿 ADB 无线调试全攻略:USB 转 WiFi 一键连接
android·前端
律宏阔1 小时前
Android WebRTC + H.265 适配记录
android
mmsx1 小时前
MapLibre 实战 08|GPS 点漂了几百米才被发现:GCJ-02 纠偏原理与"转两次"陷阱
android·前端
春夏与冬1 小时前
Android : apktool
android
YF02111 小时前
如何验证App预置为特权App功能正常?
android
律宏阔1 小时前
两台 Android 开发板的硬件序列号完全相同,如何使用 ADB 连接其中的一台?
android
律宏阔1 小时前
用 KSP + Hilt 自动注入 Android ViewBinding
android
AI2中文网3 小时前
Ai2 Starter 新版上线:Android 15、Hyper-V 与更快的模拟器体验
android
挂科边缘3 小时前
Android Studio 保姆级安装教程,Windows 电脑上安装 Android Studio
android·windows·android studio
Danny_姜3 小时前
Android Studio Quail 4 稳定版发布:本地 Gemma 4 + Android Skills
android·ide·android studio