android - 如何为 TextView 的每个字符设置阴影/发光效果

标签 android canvas textview

我正在图像上写文字并将该图像保存到 SD 卡。我希望图像文本显示为这样 enter image description here .我尝试使用自定义 TextView 并在 onDraw() 方法中应用以下逻辑

 package com.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

public class BlackStrokeTextView extends TextView {

    private TextPaint mStrokePaint;

    public BlackStrokeTextView(Context context) {
        super(context);
        init(null);
    }

    public BlackStrokeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public BlackStrokeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    public void init(AttributeSet attrs) {
         // lazy load
        if (mStrokePaint == null) {
            mStrokePaint = new TextPaint();
        }

     // copy
        mStrokePaint.setTextSize(getTextSize());
        mStrokePaint.setTypeface(getTypeface());
        mStrokePaint.setFlags(getPaintFlags());

        mStrokePaint.setTypeface(Typeface.createFromAsset(getResources().getAssets(), "fonts/impact.ttf"));

        // custom
        mStrokePaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mStrokePaint.setColor(Color.BLACK);
        mStrokePaint.setStrokeWidth(8);

        setTypeface(Typeface.createFromAsset(getResources().getAssets(), "fonts/impact.ttf"));

    }

    @Override
    protected void onDraw(Canvas canvas) {

        String text = getText().toString();
        float x = (getWidth() - mStrokePaint.measureText(text)) / 2;
        float y = getBaseline();
        canvas.drawText(text, x, y, mStrokePaint);
        super.onDraw(canvas);
    }

}

最佳答案

您可以将以下标签用于您的 TextView

 android:shadowColor 
 android:shadowDx
 android:shadowDy 
 android:shadowRadius

这样看How to make text glow?

关于android - 如何为 TextView 的每个字符设置阴影/发光效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23673911/

相关文章:

c# - 在 C# 中通过相同的结果在 Android 中将 Long 转换为 Byte []

android - 如何知道操作栏中的 SearchView 何时关闭?

Android 将宽度设置为 ConstraintLayout.LayoutParams.MATCH_PARENT 给出 -1

android - onGetViewFactory 未调用

c# - WPF Canvas 创建对象

Android获取Fragment宽度

javascript - 在 3 层 Canvas 上绘制图像并保存

jquery - html2canvas - 安全错误 : The operation is insecure

Android imageView 的海拔被 TextView 遮挡

android - 如何在 GridView 内的 ImageView 上放置文本?