Pregunta

Lo que quiero hacer es dibujar una línea que seguirá el dedo. He creado una vista personalizada, y tengo una onTouchEvent() que funciona.

Me puede trazar una línea estática en el método onDraw() sin muchos problemas.

No estoy muy seguro de cómo obtener la línea para dibujar como mi dedo se mueve sin embargo.

  public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            Log.e(TAG, " - DOWN -");
            Log.e(TAG, " getX: " + event.getX());
            break;
        }
        case MotionEvent.ACTION_UP: {
            Log.e(TAG, " - UP -");
            Log.e(TAG, " getX: " + event.getX());
            break;
        }
        }
        return true;
    }

¿Alguna pista ustedes que han estado haciendo un tiempo puede dar?

¿Es necesario que las coordenadas establecidas en la onTouchEvent() y constantemente invalida la vista por lo que los segmentos de línea pequeños dibujan?

Al final sólo quiero ser capaz de hacer garabatos, básicamente, en la pantalla con el dedo para este experimento.

¿Fue útil?

Solución

Esta única seguimiento hacia arriba y hacia abajo eventos. Realizar el seguimiento del evento ACTION_MOVE también. Ten en cuenta que hará un seguimiento de forma continua, incluso si el dedo de la persona no está aparentemente en movimiento. El código debe ser algo como esto:

ACTION_DOWN: Posición tienda

.

ACTION_MOVE:. Si la posición es diferente de la posición almacenada a continuación, dibuje una línea desde la posición almacenada a la posición actual, y la actualización de la posición almacenada en corriente

ACTION_UP:. Detener

En el bit ACTION_MOVE, que podría ser una buena idea para comprobar si la posición es por lo menos 2 o 3 píxeles de distancia de la posición almacenada. Si vas a almacenar todos los puntos de la trama, por lo que se puede hacer algo con los datos más tarde, entonces tal vez aumentar a 10 píxeles por lo que no termina con cientos de puntos para una línea simple.

Otros consejos

Esto es lo que terminé haciendo. Espero que esto ayuda a algunos otros principiantes por ahí a empezar.

Tengo una clase Sprite que representa el objeto que desea mover en la pantalla:

   public class Sprite {
    private final String TAG = "Sprite";
    private Drawable drawable;
    private int x; // the X coordinate
    private int y; // the Y coordinate
    private boolean touched; // if droid is touched/picked up
    private Speed speed; // the speed with its directions

    public Sprite(Drawable drawable, int x, int y) {
        this.drawable = drawable;
        this.x = x;
        this.y = y;
        this.speed = new Speed();
    }

    public void draw(Canvas canvas) {
        drawable.setBounds(new Rect(x, y, x+drawable.getIntrinsicWidth(), y+drawable.getIntrinsicHeight()));
        drawable.draw(canvas);
    }

    public void move() {
        if (!touched) {
            x += (speed.getXv() * speed.getxDirection());
            y += (speed.getYv() * speed.getyDirection());
        }
    }

    public void handleActionDown(int eventX, int eventY) {
        if (eventX >= (x - bitmap.getWidth() / 2) && (eventX <= (x + bitmap.getWidth() / 2))) {
            if (eventY >= (y - bitmap.getHeight() / 2) && (y <= (y + bitmap.getHeight() / 2))) {
                // droid touched
                setTouched(true);
            } else {
                setTouched(false);
            }
        } else {
            setTouched(false);
        }
    }
}

A continuación, tengo un bucle principal del juego. Que recorra y pide de mi mainPanel render y actualizar los métodos que tener este aspecto:

    public void render(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    sprite.draw(canvas);
}

public void update() {
    sprite.move();
}

La posición de donde se moverá el sprite se maneja en la captura de eventos de movimiento:

        if (event.getAction() == MotionEvent.ACTION_MOVE) {
        // the gestures
        if (sprite.isTouched()) {
            sprite.setX((int) event.getX());
            sprite.setY((int) event.getY());
        }
    }

Con suerte que es útil. Si está demasiado inclinada hacia mucho y hay algo que no te avísame.

El siguiente paso, por lo que el objeto sigue la línea!

Un evento táctil está asociado con una lista de los recuentos puntero recuperables como la siguiente:

     int p = event.getPointerCount();

iterar sobre estos y puntos dibujo puede causar un continuo línea que aparezca

if (event.getAction() == MotionEvent.ACTION_MOVE
    || event.getAction() == MotionEvent.ACTION_DOWN) {

  int p = event.getPointerCount();
     for (int i = 0; i < p; i++) { 
       c.drawPoint(event.getX(i), event.getY(i), paint);
     }
}

Suponiendo paint ya está establecido y c es el lienzo, que puede necesitar ser bloqueado (EG en una aplicación multihilo), antes de la elaboración en él.

Para los novatos este código le ayudará a crear imagen Doodle y exportarlo imagen PNG en Aquí está el código completo y esto la clase con actividad contiene una clase Ver también ..

public class MainActivity extends Activity {
    private Bitmap DrawBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint DrawBitmapPaint;
    RelativeLayout Rl;
    CustomView View;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View = new CustomView(this);
        Rl = (RelativeLayout) findViewById(R.id.Rel);
        Rl.addView(View);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(getResources()
                .getColor(android.R.color.holo_green_dark));
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(20);

    }

    private Paint mPaint;

    public class CustomView extends View {

        @SuppressWarnings("deprecation")
        public CustomView(Context c) {

            super(c);
            Display Disp = getWindowManager().getDefaultDisplay();
            DrawBitmap = Bitmap.createBitmap(Disp.getWidth(), Disp.getHeight(),
                    Bitmap.Config.ARGB_4444);

            mCanvas = new Canvas(DrawBitmap);

            mPath = new Path();
            DrawBitmapPaint = new Paint(Paint.DITHER_FLAG);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            setDrawingCacheEnabled(true);
            canvas.drawBitmap(DrawBitmap, 0, 0, DrawBitmapPaint);
            canvas.drawPath(mPath, mPaint);
            canvas.drawRect(mY, 0, mY, 0, DrawBitmapPaint);
        }

        private float mX, mY;
        private static final float TOUCH_TOLERANCE = 4;

        private void touch_start(float x, float y) {
            mPath.reset();
            mPath.moveTo(x, y);
            mX = x;
            mY = y;
        }

        private void touch_move(float x, float y) {
            float dx = Math.abs(x - mX);
            float dy = Math.abs(y - mY);
            if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
                mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
                mX = x;
                mY = y;
            }
        }

        private void touch_up() {
            mPath.lineTo(mX, mY);

            mCanvas.drawPath(mPath, mPaint);

            mPath.reset();
        }

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

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
            }
            return true;
        }

    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        mPaint.setXfermode(null);
        switch (item.getItemId()) {
        case R.id.erase: 
               mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
               break;
        case R.id.DELETE: 
             View =  new CustomView(this);
               break;
        case R.id.draw: 
               mPaint.setXfermode(null);

               break;
        case R.id.Save:
            String pattern = "mm ss";
            SimpleDateFormat formatter = new SimpleDateFormat(pattern);
            String time = formatter.format(new Date());
            String path = ("/d-codepages" + time + ".png");

            File file = new File(Environment.getExternalStorageDirectory()
                    + path);

            try {
                DrawBitmap.compress(Bitmap.CompressFormat.PNG, 100,
                        new FileOutputStream(file));
                Toast.makeText(this, "File Saved ::" + path, Toast.LENGTH_SHORT)
                        .show();
            } catch (Exception e) {
                Toast.makeText(this, "ERROR" + e.toString(), Toast.LENGTH_SHORT)
                        .show();
            }

        }
        return super.onOptionsItemSelected(item);
    }

}

También puedes ver la clase Path Java. Se puede utilizar esta ruta para dibujar ... como se mueve el dedo por la pantalla. con cada actualización (sin embargo decide implementar esta forma - cada cierto número de píxeles desde la última actualización, por ejemplo) se agrega la coordenada x, y de su camino y volver a hacer el camino total a través de un bucle. sólo una idea que estoy jugando con ahora.

Su sido un tiempo, pero este post todavía recibe algunos puntos de vista, así que pensé voy a publicar algunas cosas útiles:

Tutorial sobre cómo hacer que un objeto sigue una línea: http://www.rengelbert.com/tutorial.php?id=182

Este es un buen motor de juego gratuito que los anteriores usos tutorial también: http://libgdx.badlogicgames.com/

Espero que esto ayude a alguien por!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top