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

相关推荐
AirDroid_cn3 小时前
OPPO手机怎样被其他手机远程控制?两台OPPO手机如何相互远程控制?
android·windows·ios·智能手机·iphone·远程工作·远程控制
尊治3 小时前
手机电工仿真软件更新了
android
xiangzhihong86 小时前
使用Universal Links与Android App Links实现网页无缝跳转至应用
android·ios
车载应用猿7 小时前
基于Android14的CarService 启动流程分析
android
没有了遇见7 小时前
Android 渐变色实现总结
android
雨白10 小时前
Jetpack系列(四):精通WorkManager,让后台任务不再失控
android·android jetpack
mmoyula12 小时前
【RK3568 驱动开发:实现一个最基础的网络设备】
android·linux·驱动开发
sam.li13 小时前
WebView安全实现(一)
android·安全·webview
移动开发者1号13 小时前
Kotlin协程超时控制:深入理解withTimeout与withTimeoutOrNull
android·kotlin
程序员JerrySUN14 小时前
RK3588 Android SDK 实战全解析 —— 架构、原理与开发关键点
android·架构