有时候我们需要为TextView添加一些风采,需要有一个边框,就像相册有个边框一样。其实这个很简单的,思路就是在画布canvase上面画两个形状,画的第二个是用覆盖第一个的,只要画的第二个面积小一点,不完全覆盖第一个的形状,那么达到边框的含义啦。直接上代码吧
public class MyTextView extends TextView { Paint paint1,paint2; public MyTextView(Context context) { super(context); initView(); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } public MyTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initView(); } @Override protected void onDraw(Canvas canvas) { canvas.drawRect(0,0,getMeasuredWidth(),getMeasuredHeight(),paint1); canvas.drawRect(10,10,getMeasuredWidth() - 10,getMeasuredHeight() - 10,paint2); canvas.save(); canvas.translate(10,0); canvas.restore(); super.onDraw(canvas); } private void initView(){ paint1 = new Paint(); paint1.setColor(getResources().getColor(android.R.color.darker_gray)); paint1.setStyle(Paint.Style.FILL); paint2 = new Paint(); paint2.setColor(getResources().getColor(android.R.color.black)); paint2.setColor(ContextCompat.getColor(getContext(), android.R.color.holo_red_light)); } }然后在需要的xml里面,用上这个就可以了。