前言:
自定義控件一直都是高手的象征,自己早就想掌握這項技能,但看了很多案例和入門博客,仍然覺得高不可攀。今天再次下定決心,開始動手,才發現,也不過如此。這也與我最近一段時間對android知識掌握的層次越來越深有關系。自定義控件設計的知識點很多,我認為很多人無法掌握是因為很多知識點沒有學到位,所以很多時候覺得不知道從哪里入手。如果知識點都掌握了,自己動手,我相信很快可以入門的。準備寫一個系列的自定義控件文章,分別對幾種自定義控件進行實踐。
本文沒有介紹各個知識點的基礎知識,知識介紹了如何結合運用。
思路:
繼承TextView,重寫onDraw方法,需要繪制一個邊框,然后在控件里繪制一個搜索的icon,然后在其后繪制設置的文字,同時
需要將圖標和文字居中。
涉及到的知識點:
1.如何畫一個邊框
intpadding =this.getPaddingBottom();
intwidth = getWidth();
intheight = getMeasuredHeight();
inticonwidth = height -2*padding;
canvas.drawRoundRect(0,0, width,height,10,10,mPaint1);
canvas.drawRoundRect(1,1, width -1, height -1,10,10,mPaint2);
2.如何計算字體的高度
Paint.FontMetrics fm =txtPaint.getFontMetrics();
int fontheight = fm.bottom-fm.top;
3.如何將文字繪制居中
floatx = (width -txtPaint.measureText(getText().toString())-iconwidth-10)/2;
Paint.FontMetrics fm =txtPaint.getFontMetrics();
floaty = (height -(fm.bottom+fm.top))/2;
canvas.drawText(this.getText().toString(),x+iconwidth+10,y,txtPaint);
參考文章http://blog.csdn.net/mq2856992713/article/details/52327938
4.繪制圖片
Bitmap bit = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.find_search);
floatx = (width -txtPaint.measureText(getText().toString())-iconwidth-10)/2;
mDestRect=newRect((int)x, padding, (int) (x+height-2*padding), height -padding);
canvas.drawBitmap(bit,null,mDestRect,mPaint2) ;
源碼:
在構造函數中初始化畫筆
**mPaint1=newPaint();**
mPaint1.setColor(getResources().getColor(android.R.color.darker_gray));
mPaint1.setStyle(Paint.Style.FILL);
mPaint2=newPaint();
mPaint2.setColor(getResources().getColor(R.color.white));
mPaint2.setStyle(Paint.Style.FILL);
//文字畫筆
txtPaint=newPaint();
txtPaint.setColor(this.getCurrentTextColor());
txtPaint.setStyle(Paint.Style.FILL);
txtPaint.setTextSize(this.getTextSize());
在onDraw中,進行繪制
protected voidonDraw(Canvas canvas) {
//為搜索框加上邊框
intpadding =this.getPaddingBottom();
intwidth = getWidth();
intheight = getMeasuredHeight();
inticonwidth = height -2*padding;
canvas.drawRoundRect(0,0, width,height,10,10,mPaint1);
canvas.drawRoundRect(1,1, width -1, height -1,10,10,mPaint2);
//為搜索框加上搜索圖標
Bitmap bit = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.find_search);
floatx = (width -txtPaint.measureText(getText().toString())-iconwidth-10)/2;
mDestRect=newRect((int)x, padding, (int) (x+height-2*padding), height -padding);
canvas.drawBitmap(bit,null,mDestRect,mPaint2) ;
//計算字體的高度,并且繪制文字
Paint.FontMetrics fm =txtPaint.getFontMetrics();
floaty = (height -(fm.bottom+fm.top))/2;
canvas.drawText(this.getText().toString(),x+iconwidth+10,y,txtPaint);
}
其實,如果知識點都掌握了很簡單,這篇文章主要作為一個記錄和對自己的督促,讓觀者見笑了。