2015-10-17 38 views
0

我成功地在畫布上添加了一個橢圓形狀,但是現在我想添加兩個矩形,但由於某些原因它們不會添加到畫布中。橢圓形是一個移動的球,矩形是「背景」的靜態元素。一個矩形應該是一個地板,另一個矩形應該是運動物體,球的障礙物。將多個元素繪製到畫布上

我試圖想象它的圖像:

Result

這是代碼,mBack和小怪我試圖添加的矩形。

AnimatedView animatedView = null; 
ShapeDrawable mDrawable = new ShapeDrawable(); 
ShapeDrawable mBack = new ShapeDrawable(); 
ShapeDrawable mJump = new ShapeDrawable(); 
public static int x; 
public static int y; 
public class AnimatedView extends ImageView { 

    static final int width = 50; 
    static final int height = 50; 

    public AnimatedView(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 

     mDrawable = new ShapeDrawable(new OvalShape()); 
     mBack = new ShapeDrawable(new RectShape()); 
     mObs = new ShapeDrawable(new RectShape()); 
     mDrawable.getPaint().setColor(0xffffAC23); 
     //mDrawable.setBounds(x, y, x + width, y + height); 
     mDrawable.setBounds(y, x, y + width, x + height); 
     mBack.setBounds(100, 100, 100, 100); 
     mObs.setBounds(120,120,120,120); 

    } 

    @Override 
    protected void onDraw(Canvas canvas) { 

     mDrawable.setBounds(y, x, y + width, x + height); 
     mBack.draw(canvas); 
     mDrawable.draw(canvas); 
     invalidate(); 
    } 
} 

mDrawable將被添加,但mBack或mObs不是。將setBounds添加到onDraw也不會改變事物。

+0

代碼中缺少一些上下文; x和y他們在哪裏定義?繪圖的定義在哪裏? – abbath

+0

對不起,現在已修復。 – Banana

回答

1

您設置邊界的方式是錯誤的。定義的setBounds方法的定義是在這裏:

setBounds(int left, int top, int right, int bottom) 

兩個矩形你將其設置爲

mBack.setBounds(100, 100, 100, 100); 
mObs.setBounds(120,120,120,120); 

這意味着你是左,右角落是相同的,頂部和底部都是一樣的,所以你沒有看到你的矩形。

將其設置這樣的事情,那麼你將看到你的矩形

mBack.setBounds(100, 100, 300, 400); 

,並呼籲在的onDraw方法既矩形形狀繪製方法。

+0

另外,他不是在mObs上調用draw(),而是在onDraw()中設置邊界。 – showp1984

+0

是的。他應該畫兩個矩形形狀。更新了我的答案。 – krrish

+0

哦,我完全誤解了setBounds的行爲(因爲我認爲整數值的定位不是端點)。感謝您的回答,將您標記爲正確! – Banana

0

看來問題在於,對於mBack,您將邊界定義爲零像素(起始端以(100,100)結尾),對於mObs也是如此,但是您也沒有調用draw。