2015-10-17 61 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。