2010-10-28 17 views
26

Estoy tratando de desarrollar una clase de gráfico circular simple para Android. Por ahora, puede tomar un mapa de etiquetas y valores y dibujar el gráfico circular. Todavía tengo que agregar las leyendas para el pastel, que es donde tengo que colocar los textos cerca de pequeños rectángulos en la esquina de la pantalla. Cualquier ayuda apreciada, ya que soy nuevo en el desarrollo de Android.¿Cómo dibujar texto en lienzo?

Respuesta

1

Otra forma (posiblemente mejor) para dibujar texto en un lienzo es utilizar un StaticLayout. Esto maneja el texto multilínea cuando sea necesario.

String text = "This is some text."; 

TextPaint textPaint = new TextPaint(); 
textPaint.setAntiAlias(true); 
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density); 
textPaint.setColor(0xFF000000); 

int width = (int) textPaint.measureText(text); 
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false); 
staticLayout.draw(canvas); 

El TextPaint y StaticLayout fueron instanciado justo antes de ser utilizados aquí en aras de la ilustración. Sin embargo, hacerlo en onDraw perjudicaría el rendimiento. Here is a better example mostrándolos en el contexto de una vista personalizada que dibuja su propio texto.

6

Solía ​​haber otra respuesta aquí que se eliminó porque era solo un enlace. El enlace original es here. El código es básicamente el mismo, pero eliminé las partes de dibujo que no son de texto y también amplié los tamaños para que funcionen mejor en las densidades de pantalla modernas.

Esto solo muestra algunas cosas que puede hacer con el dibujo de texto.

enter image description here

Aquí es el código de actualización:

public class MainActivity extends AppCompatActivity { 

    DemoView demoview; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     demoview = new DemoView(this); 
     setContentView(demoview); 
    } 

    private class DemoView extends View { 
     public DemoView(Context context){ 
      super(context); 
     } 

     @Override protected void onDraw(Canvas canvas) { 
      super.onDraw(canvas); 

      // custom drawing code here 
      // remember: y increases from top to bottom 
      // x increases from left to right 
      int x = 0; 
      int y = 0; 
      Paint paint = new Paint(); 
      paint.setStyle(Paint.Style.FILL); 

      canvas.save(); 
      canvas.translate(100, 200); 

      // make the entire canvas white 
      canvas.drawColor(Color.WHITE); 

      // draw some text using STROKE style 
      paint.setStyle(Paint.Style.STROKE); 
      paint.setStrokeWidth(1); 
      paint.setColor(Color.MAGENTA); 
      paint.setTextSize(100); 
      canvas.drawText("Style.STROKE", 0, 0, paint); 

      canvas.translate(0, 200); 

      // draw some text using FILL style 
      paint.setStyle(Paint.Style.FILL); 
      //turn antialiasing on 
      paint.setAntiAlias(true); 
      //paint.setTextSize(30); 
      canvas.drawText("Style.FILL", 0, 0, paint); 

      canvas.translate(0, 200); 

      // draw some rotated text 
      // get text width and height 
      // set desired drawing location 
      x = 75; 
      y = 185; 
      paint.setColor(Color.GRAY); 
      //paint.setTextSize(25); 
      String str2rotate = "Rotated!"; 

      // draw bounding rect before rotating text 
      Rect rect = new Rect(); 
      paint.getTextBounds(str2rotate, 0, str2rotate.length(), rect); 
      canvas.translate(x, y); 
      paint.setStyle(Paint.Style.FILL); 
      // draw unrotated text 
      canvas.drawText("!Rotated", 0, 0, paint); 
      paint.setStyle(Paint.Style.STROKE); 
      canvas.drawRect(rect, paint); 
      // undo the translate 
      canvas.translate(-x, -y); 

      // rotate the canvas on center of the text to draw 
      canvas.rotate(-45, x + rect.exactCenterX(), 
        y + rect.exactCenterY()); 
      // draw the rotated text 
      paint.setStyle(Paint.Style.FILL); 
      canvas.drawText(str2rotate, x, y, paint); 

      //undo the translation and rotation 
      canvas.restore(); 
     } 
    } 
} 

Otra cosa que quiero tratar más adelante es drawing text along a path.

Ver también this fuller answer here que da la imagen siguiente.

enter image description here

Cuestiones relacionadas