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

时间:2014-05-15 09:12:19

标签: 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);
    }

}

1 个答案:

答案 0 :(得分:1)

您可以为TextView

使用以下标签
 android:shadowColor 
 android:shadowDx
 android:shadowDy 
 android:shadowRadius

这样看How to make text glow?