我成功地在画布上添加了椭圆形,但是现在我想再添加两个矩形,但是由于某种原因,它们没有被添加到画布中。椭圆形是移动的球,而矩形是用于“背景”的静态元素。一个矩形应作为地板,另一矩形应作为移动物体(球)的障碍物。

我试图形象化它:

java - 在 Canvas 上绘制多个元素-LMLPHP

这是代码,mBack和mOb是我要添加的矩形。

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或mOb。将setBounds添加到onDraw也不会改变任何事情。

最佳答案

您设置界限的方式是错误的。 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方法中对两个矩形都调用draw方法。

10-08 15:28