绘制多个矩形android画布

时间:2015-07-01 14:16:16

标签: android android-canvas

我试图在画布上绘制4个矩形,以便画布分成4个相等的矩形。使用我现在的代码,只绘制代码中的最后一个矩形。

这是我的活动中的代码:

 protected void onCreate(Bundle savedInstanceState) {
     ...
setContentView(new MyView(this));
 }

public class MyView extends View {

    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setFocusableInTouchMode(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        int x = getWidth();
        int y = getHeight();


        Paint paintTopLeft = new Paint();
        paintTopLeft.setStyle(Paint.Style.FILL);
        paintTopLeft.setColor(Color.WHITE);
        canvas.drawPaint(paintTopLeft);
        // Use Color.parseColor to define HTML colors
        paintTopLeft.setColor(Color.parseColor("#F44336"));
        canvas.drawRect(0,0,x / 2,y / 2,paintTopLeft);

        Paint paintTopRight = new Paint();
        paintTopRight.setStyle(Paint.Style.FILL);
        paintTopRight.setColor(Color.WHITE);
        canvas.drawPaint(paintTopRight);
        // Use Color.parseColor to define HTML colors
        paintTopRight.setColor(Color.parseColor("#2196F3"));
        canvas.drawRect(x / 2, 0, x, y / 2, paintTopRight);

    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

实际上我只看到两个用你的代码绘制的矩形。但无论如何,问题是你正在调用canvas.drawPaint,用这种颜色清除/填充整个画布。因此,您正在删除在绘制最后一个之前已经绘制的所有矩形。

此代码应该有效:

protected void onCreate(Bundle savedInstanceState) {
     ...
setContentView(new MyView(this));
 }

public class MyView extends View {

    public MyView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setFocusableInTouchMode(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);
        int x = getWidth();
        int y = getHeight();    

        Paint paintTopLeft = new Paint();
        paintTopLeft.setStyle(Paint.Style.FILL);
        paintTopLeft.setColor(Color.WHITE);
        //canvas.drawPaint(paintTopLeft);  // don't do that
        // Use Color.parseColor to define HTML colors
        paintTopLeft.setColor(Color.parseColor("#F44336"));
        canvas.drawRect(0,0,x / 2,y / 2,paintTopLeft);

        Paint paintTopRight = new Paint();
        paintTopRight.setStyle(Paint.Style.FILL);
        paintTopRight.setColor(Color.WHITE);
        // canvas.drawPaint(paintTopRight);  // don't do that
        // Use Color.parseColor to define HTML colors
        paintTopRight.setColor(Color.parseColor("#2196F3"));
        canvas.drawRect(x / 2, 0, x, y / 2, paintTopRight);    
    }
}