且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

绘制多个矩形Android画布

更新时间:2023-11-24 09:05:52

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

Actually I see only two rectangles that are drawn with your code. But anyway, the problem is that you are calling canvas.drawPaint which clears/fills the complete canvas with that color. So you are erasing all rectangles that have been drawn already just before you draw the last one.

此代码应正常工作:

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);    
    }
}