industrychanger
industrychanger

Reputation: 573

Rotate Text in Canvas

How do you rotate text that is in the canvas? I need to flip the text I have upside down.

paint.setTextSize(20); 
canvas.drawText("3AM", xStored, yStored, paint);

Upvotes: 1

Views: 9828

Answers (3)

D-Dᴙum
D-Dᴙum

Reputation: 7890

You need to rotate the canvas prior to the drawText() call:

canvas.save();  // save the current state of the canvas
canvas.rotate(180.0f); //rotates 180 degrees
canvas.drawText("3AM", xStored, yStored, paint);
canvas.restore(); //return to 0 degree

**EDIT - That will only invert it but it will be back-to-front. You actually need to mirror on the text-basline, assuming that is what you meant.

Upvotes: 7

Raghunandan
Raghunandan

Reputation: 133560

I got the solution from the comment by Romain Guy below the accepted answer

How can you display upside down text with a textview in Android?

Quoting You can just scale by -1 on the Y axis.

  @Override 
  protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);
      int cx = this.getMeasuredWidth() / 2;
      int cy = this.getMeasuredHeight() / 2;
      canvas.scale(1f, -1f, cx, cy);
      canvas.drawText("3AM", cx, cy, p);


}

enter image description here

Complete Example:

public class SView extends View {

    Paint p,paint; 
    public SView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        p = new Paint();
        p.setColor(Color.RED);
        p.setTextSize(40);
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setTextSize(40);
    }
  @Override 
  protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);
      int cx = this.getMeasuredWidth() / 2;
      int cy = this.getMeasuredHeight() / 2;

      canvas.drawText("3AM", cx, cy, paint);
      canvas.save(); 

      canvas.scale(1f, -1f, cx, cy);
      canvas.drawText("3AM", cx, cy, p);
      canvas.restore();
}
}

Snap

enter image description here

Upvotes: 7

Nambi
Nambi

Reputation: 12042

refer this link

 int x = 75;
    int y = 185;
    paint.setColor(Color.GRAY);
    paint.setTextSize(25);
    String rotatedtext = "Rotated helloandroid :)";

    //Draw bounding rect before rotating text:

    Rect rect = new Rect();
    paint.getTextBounds(rotatedtext, 0, rotatedtext.length(), rect);
    canvas.translate(x, y);
    paint.setStyle(Paint.Style.FILL);

    canvas.drawText(rotatedtext , 0, 0, paint);
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawRect(rect, paint);

    canvas.translate(-x, -y);


    paint.setColor(Color.RED);
    canvas.rotate(-45, x + rect.exactCenterX(),y + rect.exactCenterY());
    paint.setStyle(Paint.Style.FILL);
    canvas.drawText(rotatedtext, x, y, paint);

Upvotes: 8

Related Questions