画布在android中绘制路径

时间:2013-02-26 17:56:18

标签: java android android-canvas

我是android的新手,我想制作一个简单的程序来检测触摸坐标并绘制一个圆圈和触摸路径,我制作了一个简单的程序,在触摸周围绘制一个圆圈然后跟着它,但我仍然可以做触摸的路径。当我用路径启动程序它崩溃时,当我删除它正常工作的路径...

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

}

1 个答案:

答案 0 :(得分:0)

您尚未初始化path。最有可能的是,您的程序崩溃了NullPointerException。尝试在CustomView构造函数中添加它:

path = new Path();

将来,当您发布关于Android程序崩溃的帖子时,如果您从崩溃中发布了logcat输出,那将是最有帮助的。