简体   繁体   中英

Canvas draw path in android

I am a new beginner in android and I want to make a simple program that detect touch coordinates and draw a circle and path of touch, I make a simple program that draw a circle around the touch and follow it but I still can do the path of touch. When I start the program with path it crash, when I remove the path it works normal...

public class MainActivity extends Activity {

    float x = 0;
    float y = 0;
    LinearLayout layout; //declarea variabilor pentru desenarea cercului

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //specificarea 
        layout = (LinearLayout)findViewById(R.id.layout); //gasirea id 
        layout.addView(new CustomView(MainActivity.this));
    }

    public class CustomView extends View { //crearea unei mape pentru canvas
        Bitmap mBitmap;
        Paint paint;
        Path path;

        public CustomView(Context context) {
        super(context);
        mBitmap = Bitmap.createBitmap(640, 1024, Bitmap.Config.ARGB_8888);
            paint = new Paint();
            path = new Path();
            paint.setColor(Color.BLUE);//culoare cercului desenat
            paint.setStyle(Style.FILL);
        }

    protected void onDraw(Canvas canvas) {//desenarea cercului la atingere
        super.onDraw(canvas);
        canvas.drawPath(path,paint);
        canvas.drawCircle(x, y, 25, paint);
    }

    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();

        switch (action){
            case MotionEvent.ACTION_DOWN:
                path.moveTo(event.getX(), event.getY());
                path.lineTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                x = event.getX();
                y = event.getY();
                path.lineTo(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                path.lineTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
            break;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

You are not initializing path . Most likely, your program is crashing with a NullPointerException . Try adding this inside the CustomView constructor:

path = new Path();

In the future, when you are posting about your Android program crashing, it would be most helpful if you posted the logcat output from a crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM