2015-02-23 58 views
0

我一直在爲此掙扎,最近2個小時,我無法得到這個答案。我想要我的相對佈局的中心,因爲我想用畫布在那裏畫一個圓。我已經嘗試過:無法弄清楚如何獲得相關佈局的中心

  • ViewTreeObserver.OnGlobalLayoutListener
  • 的OnStart()

這裏是我的代碼:

@SuppressLint("NewApi") 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Paint paint = new Paint(); 
    paint.setStyle(Paint.Style.FILL); 
    paint.setColor(Color.WHITE); 
    Bitmap bg = Bitmap.createBitmap(480, 500, Bitmap.Config.ARGB_8888); 
    canvas = new Canvas(bg); 
    rel = (RelativeLayout) findViewById(R.id.relPaint); 
    //canvas.drawPaint(paint); 
    paint.setColor(Color.parseColor("#CD5C5C")); 
    canvas.drawCircle(centreX, centreY, 50, paint); 
    int sdk = android.os.Build.VERSION.SDK_INT; 
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { 
     rel.setBackgroundDrawable(new BitmapDrawable(getResources(), bg)); 
    } else { 
     rel.setBackground(new BitmapDrawable(getResources(), bg)); 
    } 
} 

@Override 
protected void onStart() { 
    centreX = rel.getX() + rel.getWidth()/2; 
    centreY = rel.getY() + rel.getHeight()/2; 
    super.onStart(); 
} 

變量REL,CENTREX和centreY在全球範圍內宣佈。謝謝。

回答

1

看看Activity Lifecycle。在onStart()之前調用onCreate()。您首先繪製圓,然後計算佈局的中心。盡一切在OnCreate()

並且計算centreXcentreY這樣。

rel.post(new Runnable() { 
@Override 
    public void run() { 
    centreX = rel.getWidth()/2; 
    centreY = rel.getHeight()/2; 

    Paint paint = new Paint(); 
    paint.setStyle(Paint.Style.FILL); 
    paint.setColor(Color.WHITE); 
    Bitmap bg = Bitmap.createBitmap(480, 500, Bitmap.Config.ARGB_8888); 
    canvas = new Canvas(bg); 
    rel = (RelativeLayout) findViewById(R.id.relPaint); 
    //canvas.drawPaint(paint); 
    paint.setColor(Color.parseColor("#CD5C5C")); 
    canvas.drawCircle(centreX, centreY, 50, paint); 
    int sdk = android.os.Build.VERSION.SDK_INT; 
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { 
     rel.setBackgroundDrawable(new BitmapDrawable(getResources(), bg)); 
    } else { 
     rel.setBackground(new BitmapDrawable(getResources(), bg)); 
    } 
    } 
});