自定義view(一)

一、坐標(biāo)系:

1、屏幕坐標(biāo)系

屏幕坐標(biāo)系以手機(jī)屏幕的左上角為坐標(biāo)原點(diǎn),過的原點(diǎn)水平直線為X軸,向右為正方向;過原點(diǎn)的垂線為Y軸,向下為正方向。


2、View坐標(biāo)系


View坐標(biāo)系以父視圖的左上角為坐標(biāo)原點(diǎn),過的原點(diǎn)水平直線為X軸,向右為正方向;過原點(diǎn)的垂線為Y軸,向下為正方向。


View內(nèi)部擁有四個函數(shù),用于獲取View的位置

getTop();//View的頂邊到其Parent View的頂邊的距離,即View的頂邊與View坐標(biāo)系的X軸之間的距離

getLeft();//View的左邊到其Parent View的左邊的距離,即View的左邊與View坐標(biāo)系的Y軸之間的距離

getBottom();//View的底邊到其Parent View的頂邊的距離,即View的底邊與View坐標(biāo)系的X軸之間的距離

getRight();//View的右邊到其Parent View的左邊的距離,即View的右邊與View坐標(biāo)系的Y軸之間的距離

圖示如下:


event.getX();//觸摸點(diǎn)相對于其所在組件坐標(biāo)系的坐標(biāo)

event.getY();event.getRawX();//觸摸點(diǎn)相對于屏幕默認(rèn)坐標(biāo)系的坐標(biāo)event.getRawY();

如下圖所示:

PS:其中相同顏色的內(nèi)容是對應(yīng)的,其中為了顯示方便,藍(lán)色箭頭向左稍微偏移了一點(diǎn).


4.核心要點(diǎn)

1.在數(shù)學(xué)中常見的坐標(biāo)系與屏幕默認(rèn)坐標(biāo)系的差別

2.View的坐標(biāo)系是相對于父控件而言的

3.MotionEvent中g(shù)et和getRaw的區(qū)別


二、繪制過程

1、構(gòu)造函數(shù)初始化

AttributeSet:是節(jié)點(diǎn)的屬性集合

defStyleAttr:默認(rèn)風(fēng)格,是指它在當(dāng)前Application或Activity所用的Theme中的默認(rèn)Style

實(shí)例如下:???

public class BaseChart extends View {? ? private String TAG = "BaseChart";? ? public BaseChart(Context context) {? ? ? ? this(context,null);? ? }? ? public BaseChart(Context context, AttributeSet attrs) {? ? ? ? this(context, attrs,R.attr.base_chart_style);? ? }? ? public BaseChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {? ? ? ? this(context, attrs, defStyleAttr,R.style.base_chart_res);? ? }? ? public BaseChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {? ? ? ? super(context, attrs, defStyleAttr, defStyleRes);? ? ? ? TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.base_chart, defStyleAttr,defStyleRes);? ? ? ? int n = array.getIndexCount();? ? ? ? for (int i=0; i" + array.getString(attr));

break;

case R.styleable.base_chart_attr2:

Log.d(TAG,"attr2 =>" + array.getString(attr));

break;

case R.styleable.base_chart_attr3:

Log.d(TAG,"attr3 =>" + array.getString(attr));

break;

case R.styleable.base_chart_attr4:

Log.d(TAG,"attr4 =>" + array.getString(attr));

break;

case R.styleable.base_chart_attr5:

Log.d(TAG,"attr5 =>" + array.getString(attr));

break;

}

}

}

}

obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)新增加的attrs屬性說明如下:

attrs:默認(rèn)屬性,告訴系統(tǒng)需要獲取那些屬性的值,有多種Value類型,這里使用string類型,如:

在attrs.xml中添加

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容