Setting the screen range on the Android canvas

I implemented a canvas for drawing on Android, but the drawing view fills the screen. I want to adjust the size of this screen. What should I do?

Once I set MyView to show with setContentView in oncreate method.

MainActivity.java

MyView view = new MyView(this);
setContentView(view);

And here is the part of painting on the canvas. However, as mentioned earlier, I want to adjust the range in which I can draw. I don’t want the whole screen to be a drawing view. MyView.java

public class MyView extends View {

    private Paint paint = new Paint();
    private Path path = new Path();
    private int x,y;

    public MyView(Context context){
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        paint.setColor(Color.BLACK);
        //STROKE속성을 이용하여 테두리...선...
        paint.setStyle(Paint.Style.STROKE);

        //두께
        paint.setStrokeWidth(3);
        //path객체가 가지고 있는 경로를 화면에 그린다...
        canvas.drawPath(path,paint);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        x = (int)event.getX();
        y = (int)event.getY();

        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                path.moveTo(x,y);
                break;
            case MotionEvent.ACTION_MOVE:
                x = (int)event.getX();
                y = (int)event.getY();
                Log.e("s",x+""+y);

                path.lineTo(x,y);
                break;
        }

        //View의 onDraw()를 호출하는 메소드...
        invalidate();

        return true;
    }
}

Answer

You can set width and height like this:

MyView view = new MyView(this);
setContentView(view);
view.setLayoutParams(new FrameLayout.LayoutParams(500, 500));

Where the FrameLayout.LayoutParams can vary for the parent ViewGroup. If the parent is LinearLayout, it should be LinearLayout.LayoutParams, and so on.

Leave a Reply

Your email address will not be published. Required fields are marked *