2011-05-28 8 views
19

¿Cómo puedo escribir texto en una imagen y luego guardarla en Android?¿Cómo escribo texto sobre una imagen en Android y la guardo?

Básicamente quiero que el usuario escriba algo en las imágenes que mi aplicación de cámara hará clic para ellas. Puedo escribir y mostrarles usando el método onDraw en la vista previa de la cámara. Pero después de que el usuario ha hecho clic en la imagen, quiero escribir el texto sobre la imagen y luego guardarla.

Respuesta

5

Tiene que implementar un lienzo que le permita al usuario dibujar sobre él y luego establecer el fondo de ese lienzo en esa imagen en particular. Esto es solo una suposición, pero está en algún lugar allí.

+0

aah eso fue fácil ... gracias :-) – nasaa

45

Puede poner EditarTexto y escribir en él, y después de la escritura, primero convertirlo en mapa de bits como:

Bitmap bmp = Bitmap.createBitmap(mEditText.getDrawingCache()); 

Ahora puede agregar imagen creada bmp a la imagen original como esto:

Llamar: Bitmap combined = combineImages(bgBitmap,bmp);

public Bitmap combineImages(Bitmap background, Bitmap foreground) { 

     int width = 0, height = 0; 
     Bitmap cs; 

     width = getWindowManager().getDefaultDisplay().getWidth(); 
     height = getWindowManager().getDefaultDisplay().getHeight(); 

     cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
     Canvas comboImage = new Canvas(cs); 
     background = Bitmap.createScaledBitmap(background, width, height, true); 
     comboImage.drawBitmap(background, 0, 0, null); 
     comboImage.drawBitmap(foreground, matrix, null); 

     return cs; 
    } 
+0

Genio, nunca tendría eso de eso. ¡Camino a seguir! – JoxTraex

+0

Si colocamos vista de texto (primer plano) dinámicamente en una vista (el ancho y el alto son más pequeños que la imagen original en Sd), al usar la imagen original 'fondo' (fondo = Mapa de bits ....), la posición de texto agregado cambió. cómo mantener la posición ?! –

+0

Consulte mi pregunta: http://stackoverflow.com/questions/29960021/keep-added-textview-position-over-imageview-when-saved –

2

Permite ayudar .. primer lugar que debe tener para usar lienzo para dibujar. Cree una vista personalizada que extienda ImageView. Aquí está el código para la función de ayudar a onDraw ..:

@Override 
    public void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
     mIcon.setBounds(0, 0, mIcon.getMinimumWidth(), 
       mIcon.getMinimumHeight()); 

     canvas.translate(mPosX, mPosY); 
     canvas.scale(mScaleFactor, mScaleFactor, canvas.getWidth() * 0.5f, 
       canvas.getWidth() * 0.5f); 
     mIcon.draw(canvas); 

     rect = canvas.getClipBounds(); 

     for (Path path : listPath) { 
      canvas.drawPath(path, paint); 

     } 

    } 

Ahora, para onTouch:

@Override 
    public boolean onTouchEvent(MotionEvent ev) { 
     // Let the ScaleGestureDetector inspect all events. 
     mScaleDetector.onTouchEvent(ev); 

     final int action = ev.getAction(); 
     switch (action & MotionEvent.ACTION_MASK) { 
     case MotionEvent.ACTION_DOWN: { 

      if (drawing) { 

       startPoint = new Point((int) ev.getX(), (int) ev.getY()); 
       path = new Path(); 
       float x = ev.getX()/mScaleFactor + rect.left; 
       float y = ev.getY()/mScaleFactor + rect.top; 
       path.moveTo(x, y); 
       path.lineTo(x, y); 

       mLastTouchX_1 = x; 
       mLastTouchY_1 = y; 
      } 

      else { 
       final float x = ev.getX(); 
       final float y = ev.getY(); 

       mLastTouchX = x; 
       mLastTouchY = y; 
       mActivePointerId = ev.getPointerId(0); 
      } 
      break; 
     } 

     case MotionEvent.ACTION_MOVE: { 

      if (drawing) { 

       float x = ev.getX()/mScaleFactor + rect.left; 
       float y = ev.getY()/mScaleFactor + rect.top; 

       path.moveTo(mLastTouchX_1, mLastTouchY_1); 
       path.lineTo(x, y); 

       mLastTouchX_1 = x; 
       mLastTouchY_1 = y; 
      } 

      else { 
       final int pointerIndex = ev 
         .findPointerIndex(mActivePointerId); 
       final float x = ev.getX(pointerIndex); 
       final float y = ev.getY(pointerIndex); 

       // Only move if the ScaleGestureDetector isn't processing a 
       // gesture. 
       if (!mScaleDetector.isInProgress()) { 
        final float dx = x - mLastTouchX; 
        final float dy = y - mLastTouchY; 

        mPosX += dx; 
        mPosY += dy; 

        invalidate(); 
       } 

       mLastTouchX = x; 
       mLastTouchY = y; 
      } 
      break; 
     } 

     case MotionEvent.ACTION_UP: { 
      path_helper_1 = new Path(); 
      path_helper_2 = new Path(); 

      endPoint = new Point((int) ev.getX(), (int) ev.getY()); 

      int left, top, right, bottom; 



      left = endPoint.x - 10; 
      top = endPoint.y - 10; 

      right = endPoint.x + ((endPoint.y/2)); 
      bottom = endPoint.x + ((endPoint.y/2)); 



      float dx, dy; 
      dx = endPoint.x - startPoint.x; 
      dy = endPoint.y - startPoint.y; 

      dx = dx * -1; 
      dy = dy * -1; 

      // dx = dy = 100; 

      double cos = 0.866 * .1; 
      double sin = 0.500 * .1; 

      PointF end1 = new PointF((float) (endPoint.x + (dx * cos + dy 
        * -sin)), (float) (endPoint.y + (dx * sin + dy * cos))); 
      PointF end2 = new PointF((float) (endPoint.x + (dx * cos + dy 
        * sin)), (float) (endPoint.y + (dx * -sin + dy * cos))); 

      // path.moveTo(endPoint.x, endPoint.y); 
      // 
      // path.lineTo(endPoint.x, endPoint.y); 
      // 
      // path.lineTo(end1.x, end1.y); 
      // 
      // path.moveTo(endPoint.x, endPoint.y); 
      // 
      // path.lineTo(end2.x, end2.y); 
      // 
      // 
      // listPath.add(path); 

      mActivePointerId = INVALID_POINTER_ID; 
      break; 
     } 

     case MotionEvent.ACTION_CANCEL: { 
      mActivePointerId = INVALID_POINTER_ID; 
      break; 
     } 

     case MotionEvent.ACTION_POINTER_UP: { 
      final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; 
      final int pointerId = ev.getPointerId(pointerIndex); 
      if (pointerId == mActivePointerId) { 
       // This was our active pointer going up. Choose a new 
       // active pointer and adjust accordingly. 
       final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 
       mLastTouchX = ev.getX(newPointerIndex); 
       mLastTouchY = ev.getY(newPointerIndex); 
       mActivePointerId = ev.getPointerId(newPointerIndex); 
      } 
      break; 
     } 
     } 
     invalidate(); 

     return true; 
    } 

también hacen una clase privada si se desea implementar la funcionalidad de zoom de esta manera:

private class ScaleListener extends 
      ScaleGestureDetector.SimpleOnScaleGestureListener { 
     @Override 
     public boolean onScale(ScaleGestureDetector detector) { 

      if (zoom) { 
       mScaleFactor *= detector.getScaleFactor(); 

       // Don't let the object get too small or too large. 
       mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); 
      } 
      invalidate(); 
      return true; 
     } 
    } 
} 

Tome la idea del código anterior y realice cambios de acuerdo con sus requisitos. NOTA El código anterior implementa la funcionalidad Dibujo y zoom. Si desea agregar texto sobre las imágenes, como el Dibujo de ruta, también puede dibujar texto sobre lienzo usando canvas.drawText. Haga una lista de arrays si quiere múltiples imágenes de texto.

0

Agregar texto en mapa de bits:

public Bitmap drawTextToBitmap(Context gContext, 
    int gResId, 
    String gText) { 
    Resources resources = gContext.getResources(); 
    float scale = resources.getDisplayMetrics().density; 
    Bitmap bitmap = 
     BitmapFactory.decodeResource(resources, gResId); 

    android.graphics.Bitmap.Config bitmapConfig = 
     bitmap.getConfig(); 
    // set default bitmap config if none 
    if(bitmapConfig == null) { 
    bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; 
    } 
    // resource bitmaps are imutable, 
    // so we need to convert it to mutable one 
    bitmap = bitmap.copy(bitmapConfig, true); 

    Canvas canvas = new Canvas(bitmap); 
    // new antialised Paint 
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
    // text color - #3D3D3D 
    paint.setColor(Color.rgb(61, 61, 61)); 
    // text size in pixels 
    paint.setTextSize((int) (14 * scale)); 
    // text shadow 
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE); 

    // draw text to the Canvas center 
    Rect bounds = new Rect(); 
    paint.getTextBounds(gText, 0, gText.length(), bounds); 
    int x = (bitmap.getWidth() - bounds.width())/2; 
    int y = (bitmap.getHeight() + bounds.height())/2; 

    canvas.drawText(gText, x, y, paint); 

    return bitmap; 
} 

Fuente: http://www.skoumal.net/en/android-how-draw-text-bitmap/

Añadir texto de múltiples líneas de mapa de bits:

public Bitmap drawMultilineTextToBitmap(Context gContext, 
            int gResId, 
            String gText) { 

    // prepare canvas 
    Resources resources = gContext.getResources(); 
    float scale = resources.getDisplayMetrics().density; 
    Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId); 

    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig(); 
    // set default bitmap config if none 
    if(bitmapConfig == null) { 
    bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; 
    } 
    // resource bitmaps are imutable, 
    // so we need to convert it to mutable one 
    bitmap = bitmap.copy(bitmapConfig, true); 

    Canvas canvas = new Canvas(bitmap); 

    // new antialiased Paint 
    TextPaint paint=new TextPaint(Paint.ANTI_ALIAS_FLAG); 
    // text color - #3D3D3D 
    paint.setColor(Color.rgb(61, 61, 61)); 
    // text size in pixels 
    paint.setTextSize((int) (14 * scale)); 
    // text shadow 
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE); 

    // set text width to canvas width minus 16dp padding 
    int textWidth = canvas.getWidth() - (int) (16 * scale); 

    // init StaticLayout for text 
    StaticLayout textLayout = new StaticLayout(
    gText, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false); 

    // get height of multiline text 
    int textHeight = textLayout.getHeight(); 

    // get position of text's top left corner 
    float x = (bitmap.getWidth() - textWidth)/2; 
    float y = (bitmap.getHeight() - textHeight)/2; 

    // draw text to the Canvas center 
    canvas.save(); 
    canvas.translate(x, y); 
    textLayout.draw(canvas); 
    canvas.restore(); 

    return bitmap; 
} 

Fuente: http://www.skoumal.net/en/android-drawing-multiline-text-on-bitmap/

Cuestiones relacionadas