2016-02-11 100 views
0

我想畫一個自定義視圖中十字線的正確尺寸,獲取自定義視圖

@Override 
public void onWindowFocusChanged(boolean hasWindowFocus) 
{ super.onWindowFocusChanged(hasWindowFocus); 
    top=this.getTop()+(this.getTop()/10); 
    bottom=this.getBottom()-(this.getBottom()/10); 
    left=this.getLeft()+(this.getLeft()/10); 
    right=this.getRight()-(this.getRight()/10); 
    Log.e("graph",getTop()+":"+top+","+this.getBottom()+":"+bottom+","+this.getLeft()+":"+left+","+this.getRight()+":"+right); 
} 

我使用這個代碼來獲取上,下,左,視右座標和調整第十部分作爲填充。

的onDraw方法內,

canvas.drawLine(left, (bottom - top)/2, right, (bottom - top)/2, paint); 
    canvas.drawLine((right-left)/2,top,(right-left)/2,bottom,paint); 

這兩種方法來繪製該水平居中和垂直居中的線。我正在手機屏幕上顯示此圖。

enter image description here

我想有水平居中和垂直居中行,我該怎麼辦?

回答

0

頂部,底部,左側和右側屬性不描述視圖的尺寸。他們描述視圖在其容器內的位置。

相反,在視圖對象上使用getWidth()和getHeight(),而不是使用該信息來查找尺寸和繪圖。

+0

在http://developer.android.com/ reference/android/view/View.html,它寫成「例如,調用getRight()類似於下面的計算:getLeft()+ getWidth()」所以我不thisnk它會有所作爲。 –

0

頂部,底部,都是座標相對於IST容器視圖的位置, 我認爲你需要像畫線:

canvas.drawLine(this.getLeft(), (this.getTop() + this.getBottom())/2, this.getRight(), (this.getTop() + this.getBottom())/2, paint); 
canvas.drawLine((this.getLeft()+this.getRight())/2, this.getTop(), (this.getLeft()+this.getRight())/2, this.getBottom(), paint);