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);
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);
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);
}
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
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);
You need to rotate the canvas prior to the drawText() call:
canvas.save(); // svare 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.