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

相关推荐
2501_9159090616 小时前
深入解析Mock.js:功能、应用及实战案例,提升前端开发效率
android·ios·小程序·https·uni-app·iphone·webview
流星白龙18 小时前
【MySQL高阶】21.撤销表空间,撤销日志
android·mysql·adb
我命由我1234519 小时前
Android 开发,FragmentPagerAdapter 的 isViewFromObject 方法问题
android·java-ee·kotlin·android studio·android jetpack·android-studio·android runtime
weiggle19 小时前
第五篇:Modifier 解析——链式调用的艺术
android
awu的Android笔记19 小时前
Android 弱网模拟:别只会用均匀分布——三种延迟模型和两种丢包模型的原理与实现
android·tcp/ip
sensor_WU20 小时前
【Delphi】 开发 android 升级模块硬核实现
android·delphi android·android 升级·apk升级 delphi
帅次20 小时前
Kotlin MVVM 实战入门:从分层到状态闭环
android·kotlin·android studio·android jetpack
YF021120 小时前
Android BLE 信号强度获取与 底层原理深度解析
android·蓝牙
随遇丿而安20 小时前
第7周:RecyclerView 高级功能与列表硬核优化
android
qq36219670520 小时前
手机App下载安装完全指南:2026最新教程(Android & iOS)
android·ios·智能手机