为什么我的画布不能超过100 * 100像素?

时间:2016-02-02 00:39:50

标签: android canvas ondraw

我正在编写一个绘制用户点击的矩形的应用程序。但是我的画布仅适用于屏幕左上角的前100 * 100像素。当应用程序启动时,它工作正常,但在用户第一次触摸后,它只能在屏幕的左上角100 * 100像素中工作。

 input = atoi(argv[1]);

公共类MainActivity扩展了Activity {

package com.example.sudokutest;

}

public static int x=0;
public static int y=0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(new Myview(MainActivity.this));

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    Display dispaly=getWindowManager().getDefaultDisplay();
    Point size=new Point();
    dispaly.getSize(size);

    x=size.x;
    y=size.y-40; //Subtracting the NotificationBar from height not accurately


}       

这是xml文件。它是空白的,它应该用ondraw方法填充。

public class Myview extends View {

 public Rect selRect = new Rect();

    public Myview(Context context) {
        super(context);
        selRect.set(0,0,300,400);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Paint paint = new Paint();
        paint.setColor(getResources().getColor(R.color.puzzle_background));
        canvas.drawRect(selRect,paint);
    }

    @Override
    public  boolean onTouchEvent(MotionEvent event) {
        final int a = (int)event.getX();
        final int b = (int)event.getY();

        int eventaction = event.getAction();

        switch (eventaction) {
            case MotionEvent.ACTION_DOWN:
                Toast.makeText(getContext(),(CharSequence)("ACTION_DOWN AT COORDS "+"X: "+a+" Y: "+b),Toast.LENGTH_SHORT).show();
                selRect.set(a,b,100,100);
                invalidate();
                break;

            case MotionEvent.ACTION_MOVE:
                Toast.makeText(getContext(), "MOVE "+"X: "+a+" Y: "+b, Toast.LENGTH_SHORT).show();
                break;

            case MotionEvent.ACTION_UP:
                Toast.makeText(getContext(), "ACTION_UP "+"X: "+a+" Y: "+b, Toast.LENGTH_SHORT).show();
                break;
            }

        return super.onTouchEvent(event);
    }

}

2 个答案:

答案 0 :(得分:0)

在onTouchEvent中

你在ACTION_DOWN中调用它:

selRect.set(a,b,100,100);

你永远不会重置它。

答案 1 :(得分:0)

如果您想在另一个视图上添加自定义画布类,并使用相对或框架布局,只需将画布添加到顶部...

假设您的主RelativeLayout名为main_layout,而您的CustomView名为drawable,您可以将drawable添加到main_layout中,如此...

            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            main_layout.addView(drawable, params);