How can I set text direction (rotate) on Canvas. Vertical for example.
Asked
Active
Viewed 2,243 times
3 Answers
1
You can use the rotate()
method to specify the rotation of the elements that are going to be painted next.
Additional note: Be sure to read the rest of the Canvas
documentation as well, as it has lots of methods to manipulate it (assuming you need more than rotating texts at some stage)

Veger
- 37,240
- 11
- 105
- 116
1
Here is one simple vertical text implementation and rotation.
public class VerticalTextView extends TextView{
final boolean topDown;
public VerticalTextView(Context context, AttributeSet attrs){
super(context, attrs);
final int gravity = getGravity();
if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
topDown = false;
}else
topDown = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
@Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
if(topDown){
canvas.translate(getWidth(), 0);
canvas.rotate(90);
}else {
canvas.translate(0, getHeight());
canvas.rotate(-90);
}
canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
}
}
By default, rotated text is from top to bottom. If you set
android:gravity="bottom"
then it's drawn from bottom to top.

user1954492
- 495
- 3
- 13
-
For me it's very complicated example, and I have seen it before here http://stackoverflow.com/questions/9262494/draw-text-vertically-on-canvas. I don't understand, while it does't work in my code, but it is not important now. I've added my solution, it works and very simple. Thanks! – Konstantin.Efimenko Jan 24 '13 at 12:33
0
simpest way is:
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.rotate(90, x, y);
canvas.drawText("text", x, y, textPaint);
}

Konstantin.Efimenko
- 1,242
- 1
- 14
- 38