当前位置: 首页 > article >正文

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

效果如下

自定义两个属性

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

实现类

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


http://www.kler.cn/news/356545.html

相关文章:

  • 【vue】⾃定义指令+插槽+商品列表案例
  • Windows git 配置
  • HarmonyOS NEXT 应用开发实战(五、页面的生命周期及使用介绍)
  • 人工智能 MiniCPM-V-8B-2.6:单图、多图、视频多模态大模型
  • js 鼠标拖动canvas画布
  • RHCE第三次笔记SSH
  • ParallelsDesktop20最新版本虚拟机 一键切换系统 游戏娱乐两不误
  • 【服务器虚拟化】
  • linux一二三章那些是重点呢
  • SCI英文文献阅读工具【全文翻译】【逐句翻译】
  • python 猜数字游戏
  • Tomcat日志文件详解及catalina.out日志清理方法
  • 鸿蒙ArkTS实用开发技巧: 提高效率的关键知识点
  • 12.个人博客系统(Java项目基于spring和vue)
  • 尚硅谷rabbitmq 2024 Federation配置 第60节答疑
  • 【如何获取股票数据10】Python、Java等多种主流语言实例演示获取股票行情api接口之沪深A股历史分时KDJ数据获取实例演示及接口API说明文档
  • 「从零开始的 Vue 3 系列」:第十二章——Element Plus 组件的二次封装实践(保姆式)
  • 母婴商城(论文+源码)_kaic
  • 音视频入门基础:H.264专题(18)——AVCDecoderConfigurationRecord简介
  • conda打包