2011-04-01 10 views
11

Quiero dibujar texto en rectángulo en el centro (horizontal y vertical). Si hay demasiado texto que lo recorte, lo que no encaja en rect.Android dibujar texto en un rectángulo en el centro y recortarlo si es necesario

He intentado hacerlo como this example show, pero sin suerte.

¿Alguna idea?

+0

Comprobar esto, es cierto lo mismo que lo que necesita, http://stackoverflow.com/questions/13285510/how-to-overlay-image-with- multiline-texttext-will-be-in-center-of-the-canvas/13287621 # 13287621 – Atrix1987

+0

Prueba esto, es trabajo para mí: http://stackoverflow.com/questions/11120392/android-center-text-on- lienzo –

+0

Este trabajo para mí, pruébalo. [http://stackoverflow.com/questions/11120392/android-center-text-on-canvas](http://stackoverflow.com/questions/11120392/android-center-text-on- canvas) –

Respuesta

0

¿Qué tal esto?

<FrameLayout 
    android:id="@+id/frameLayout1" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_height="40dp" 
     android:layout_width="100dp" 
     android:layout_gravity="center" 
     android:text="TextViewqqqqqqqqqqqwwww" 
     android:inputType="text"> 
    </TextView> 
</FrameLayout> 
+0

Quiero dibujar texto sobre lienzo. Dinamicamente. basado en el tamaño del rectángulo – zmeda

5

esta función funcionó para mí.

private void drawDigit(Canvas canvas, int textSize, float cX, float cY, int color, String text) { 
     Paint tempTextPaint = new Paint(); 
     tempTextPaint.setAntiAlias(true); 
     tempTextPaint.setStyle(Paint.Style.FILL); 

     tempTextPaint.setColor(color); 
     tempTextPaint.setTextSize(textSize); 

     float textWidth = tempTextPaint.measureText(text); 
     //if cX and cY are the origin coordinates of the your rectangle 
     //cX-(textWidth/2) = The x-coordinate of the origin of the text being drawn 
     //cY+(textSize/2) = The y-coordinate of the origin of the text being drawn 

     canvas.drawText(text, cX-(textWidth/2), cY+(textSize/2), tempTextPaint); 
    } 
9

Prueba este

private void drawRectText(String text, Canvas canvas, Rect r) { 

    textPaint.setTextSize(20); 
    textPaint.setTextAlign(Align.CENTER); 
    int width = r.width(); 

    int numOfChars = textPaint.breakText(text,true,width,null); 
    int start = (text.length()-numOfChars)/2; 
    canvas.drawText(text,start,start+numOfChars,r.exactCenterX(),r.exactCenterY(),textPaint); 
} 
+0

Esto dibuja el texto con el centro de alineación, pero solo horizontalmente. Entonces la pregunta es cómo hacerlo verticalmente también. – ddmytrenko

Cuestiones relacionadas