本章將講解下如何自定義一個(gè)帶箭頭指向的TextView,很簡(jiǎn)單崇渗,先看下效果
image
更多全棧資源請(qǐng)?jiān)L問(wèn):https://www.leachchen.com
image
更多資訊請(qǐng)掃碼或者加入微信群:
image
那么如何實(shí)現(xiàn)呢模聋?
既然是文本,那么我們就新建一個(gè)類繼承TextView昼接;
-
上圖中TextView區(qū)域?qū)嶋H為顏色灰色的區(qū)域徒像,我們需要框定出一個(gè)圓角矩形的文本顯示區(qū)域镊逝,可用如下方式:
canvas.drawRoundRect(new RectF(getPaddingLeft() - 20,getPaddingTop() - 20,width - getPaddingRight() + 20,height - getPaddingBottom()+20),30,30,paint);
其中加20愿险,-20是讓文本在圓角矩形內(nèi)縮進(jìn),否則文本是緊貼著圓角矩形邊框的漾脂;
三角指示器繪制假颇,我們需要在布局里給該文本設(shè)置內(nèi)邊距,該邊距要能放下三角指示器骨稿,否則圓角矩形填滿TextView笨鸡,三角指示器就沒有空間顯示了,然后利用Path進(jìn)行描點(diǎn)繪制三角指示器就可以了坦冠;
全部代碼:
public class ArrowTextView extends TextView{
public ArrowTextView(Context context) {
super(context);
}
public ArrowTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ArrowTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true); //設(shè)置畫筆抗鋸齒
paint.setStrokeWidth(2); //設(shè)置線寬
paint.setColor(Color.WHITE); //設(shè)置線的顏色
int height = getHeight(); //獲取View的高度
int width = getWidth(); //獲取View的寬度
//框定文本顯示的區(qū)域
canvas.drawRoundRect(new RectF(getPaddingLeft() - 20,getPaddingTop() - 20,width - getPaddingRight() + 20,height - getPaddingBottom()+20),30,30,paint);
Path path = new Path();
//以下是繪制文本的那個(gè)箭頭
path.moveTo(width / 2, height);// 三角形頂點(diǎn)
path.lineTo(width / 2 - 20, height - getPaddingBottom()); //三角形左邊的點(diǎn)
path.lineTo(width / 2 + 20, height - getPaddingBottom()); //三角形右邊的點(diǎn)
path.close();
canvas.drawPath(path, paint);
super.onDraw(canvas);
}
}
布局代碼:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context="com.example.testview.Activity.ArrowTextViewActivity">
<com.example.testview.View.ArrowTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:padding="20dp"
android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
android:background="#666666"
/>
</android.support.constraint.ConstraintLayout>
源碼參考samples里面的TestView