通过有描边的文本和没描边的文本重叠的形式,并且两个文本为不同颜色则可达到想要的描边效果
public class StrokeTextView extends TextView {
private TextPaint strokePaint;
public StrokeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
// lazy load
if (strokePaint == null) {
strokePaint = new TextPaint();
}
// 复制原来TextViewg画笔中的一些参数
TextPaint paint = getPaint();
strokePaint.setTextSize(paint.getTextSize());
strokePaint.setFlags(paint.getFlags());
strokePaint.setTypeface(paint.getTypeface());
strokePaint.setAlpha(paint.getAlpha());
// 自定义描边效果
strokePaint.setStyle(Paint.Style.FILL_AND_STROKE);// 设置不同Style有不同效果哟
strokePaint.setColor(Color.parseColor("#cdb79e"));
strokePaint.setStrokeWidth(20);
String text = getText().toString();
//在文本底层画出带描边的文本
canvas.drawText(text, (getWidth() - strokePaint.measureText(text)) / 2, getBaseline(), strokePaint);
super.onDraw(canvas);
}
}
<com.example.textBorder.StrokeTextView
android:id="@+id/hello3"
android:text="39"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/layout_hello"
android:textColor="#acccc6"
android:textSize="70dp"
/>
Demo是android studio工程