这里也要简单说一下,这些小模块并不是我原创,也是当时查资料找到的,由于时间比较久,原文链接已经忘记了,所以这里就不列出引用链接了。不过这些代码我都修改、完善过,也添加了一些注释,希望对大家有帮助。
文字描边这个功能挺实用的,如果是单一背景下显示文字,文字描边也可起到装饰作用。如果是复杂背景下,尤其是在不同图片背景下显示文字,因为文字颜色很容易和图片背景相似,这样导致文字看不清楚,用户体验不佳。如果文字经过不同颜色描边后,文字轮廓部分一种颜色,文字内部另一种颜色,因为一般情况下,图片要么和文字轮廓颜色相近,要么和文字内部颜色相近,这样不管图片背景多复杂,文字都会整体显示。
我这里使用的方法是重写
TextView
方式。
下面是相关代码,整体比较简单,很容易懂。
继承的TextView文字描边类如下:
public class StrokeTextView extends TextView{ private TextView outlineTextView = null; public StrokeTextView(Context context){super(context);outlineTextView = new TextView(context);init();} public StrokeTextView(Context context, AttributeSet attrs) {super(context, attrs);outlineTextView = new TextView(context, attrs);init();} public StrokeTextView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);outlineTextView = new TextView(context, attrs, defStyle);init();} public void init(){TextPaint paint = outlineTextView.getPaint();paint.setStrokeWidth(3);// 描边宽度paint.setStyle(Style.STROKE);outlineTextView.setTextColor(Color.parseColor("#45c01a"));// 描边颜色outlineTextView.setGravity(getGravity());} @Overridepublic void setLayoutParams (ViewGroup.LayoutParams params){super.setLayoutParams(params);outlineTextView.setLayoutParams(params);} @Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 设置轮廓文字 CharSequence outlineText = outlineTextView.getText();if (outlineText == null || !outlineText.equals(this.getText())){ outlineTextView.setText(getText());postInvalidate();}outlineTextView.measure(widthMeasureSpec, heightMeasureSpec);} @Overrideprotected void onLayout (boolean changed, int left, int top, int right, int bottom){super.onLayout(changed, left, top, right, bottom);outlineTextView.layout(left, top, right, bottom);} @Overrideprotected void onDraw(Canvas canvas){ outlineTextView.draw(canvas);super.onDraw(canvas);}}
布局文件如下:<com.my.teststroketextview.StrokeTextViewandroid:id="@+id/test_stroketextview"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:textSize="25sp"android:textColor="@color/dark_gray"android:text="@string/hello_world" />
调用代码如下:private StrokeTextView test_stroketextview = null; @Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);test_stroketextview = (StrokeTextView)findViewById(R.id.test_stroketextview); test_stroketextview.setText("Hello world!");}
如果想更改文字描边宽度,或者描边颜色,需要修改上面的
StrokeTextView
类,当然也可以把这个类设计的更灵活些,这样就可以动态的修改描边宽度或者描边颜色。
以上就是android中文字描边功能的实现实例,希望本文对大家学习android开发有所帮助。请大家多多支持脚本之家。