2013-05-14 263 views
3

我剛剛進入Android基本繪圖。我從幾個簡單的形狀開始,但我遇到了一些問題。我想在畫布的中心畫一個圓圈。我看了幾個例子,但似乎無法使其工作。我認爲這是因爲我不太瞭解變量在哪裏。在畫布中心繪製圓圈

有人可以請解釋一下在我的屏幕中心繪製我的圈子的正確方法。這裏是我的代碼:

public class Circle extends View{ 

int width = this.getWidth(); 
int height = this.getHeight(); 

public Circle(Context context) { 
    super(context); 
    setFocusable(true); 

} 
protected void onDraw(Canvas canvas){ 
    canvas.drawColor(Color.CYAN); 
    Paint paint = new Paint(); 
    paint.setStyle(Paint.Style.FILL); 
    //canvas.drawCircle(100, 100, 50, paint); 
    canvas.drawCircle(width/2, height/2, 100, paint); 

    Display disp = ((WindowManager)this.getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 

    float radius = 0;//Radius caused an error so I initialized this variable 

    canvas.drawCircle(disp.getWidth()/2, disp.getHeight()/2, radius, paint); 

} 

}

+2

我對android編程知之甚少,但我知道半徑爲0意味着你沒有圈子。 http://en.wikipedia.org/wiki/Radius – Kevin

+0

好夠了。謝謝。 – David

+0

[Draw Circle on touch]可能重複(http://stackoverflow.com/questions/11796357/draw-circle-on-touch) – bummi

回答

8

寬度和觀點的高度都沒有的時候的getWidth()和getHeight()調用尚未初始化,只是在的onDraw使用的getWidth()和getHeight() :

canvas.drawCircle(getWidth()/2, getHeight()/2, 100, paint); 

你也可以重寫onSizeChanged並獲取視圖的寬度和高度。

PS:不要在onDraw中創建任何東西,在構造函數中創建繪畫對象。

-1

有一些對我們非常有用的鏈接,我希望他們會爲你和其他人工作。

  1. https://github.com/swapgo20/Android-Hand-Drawing
  2. https://github.com/codepath/android_guides/wiki/Basic-Painting-with-Views
  3. https://github.com/Korilakkuma/CanvasView

我希望上面的鏈接是在畫布上繪製形狀非常有用的。

我建議你使用第三個鏈接,並使用android的路徑類(http://developer.android.com/reference/android/graphics/Path.html)來繪製形狀。

0

公共無效畫圓(Graphics2D的克,INT的x,INT Y,INT半徑){

X = X-(半徑/ 2);

y = y-(radius/2);

g.fillOval(x,y,radius,radius);

}

在此,x,y是要畫出的圓畫布的位置,你可以用運動聽衆找到它,如果你要設置的x,y位置動態地希望這將幫助你