Question

I'm new in Android and I've written the following sample code.

public class Circle extends View {
    Paint paint = new Paint();
    Path path = new Path();
    private static final String s = "Hello world example";

    public Circle(Context context) {
      super(context);
      paint.setColor(Color.BLACK);
      paint.setStyle(Style.STROKE);
      paint.setStrokeWidth(2);
      paint.setAntiAlias(true);
      paint.setTextSize(30);
    }

    public void onDraw(Canvas c) {    
      path.addCircle(getWidth()/2, getHeight()/2, 180, Direction.CW);
      c.drawTextOnPath(s, path, 0, 10, paint);
      setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    } 

  }

The Canvas.drawTextOnPath() is displaying the the text beginning from the right side (I mean positive X-axis). I want to display the text from top in a clock-wise. I want to change the starting position of the text. I'm confused about Android Canvas.translate() and Canvas.scale(). Or should I use Canvas.rotate()? I've pasted the output below for clear understanding my question.enter image description here

I want to display the output in this form.

enter image description here

Was it helpful?

Solution

I've finally fixed my Canvas issue by adding the Canvas.rotate(float degrees, float px, float py) in my code before applying and Canvas methods. Below is the code.

public class Circle extends View {
    Paint paint = new Paint();
    Path path = new Path();
    private static final String s = "Hello world example";

    public Circle(Context context) {
      super(context);
      paint.setColor(Color.BLACK);
      paint.setStyle(Style.STROKE);
      paint.setStrokeWidth(2);
      paint.setAntiAlias(true);
      paint.setTextSize(30);
    }

    public void onDraw(Canvas c) {   
      c.rotate(-90, getWidth()/2, getHeight()/2);
      path.addCircle(getWidth()/2, getHeight()/2, 180, Direction.CW);
      c.drawTextOnPath(s, path, 0, 10, paint);
      setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    } 
}

I tried Canvas.rotate(float degrees) before but didn't worked. However, Canvas.rotate(float degrees, float px, float py) worked!

OTHER TIPS

Instead of circle, arc can be used:

Path path = new Path(); RectF rect = new RectF(width/2 - radius, height/2 - radius, width/2 + radius, height/2 + radius); path.addArc(rect 270, 270); canvas.drawTextOnPath(msg., path, 0, 0, paint);

The path can be translated, rotated and scaled by using Matrix. For example, the above code will draw the text starting from the first quadrant, i.e, from (y, 0). To start the drawing from (-y, 0) in clockwise direction,

 Path path = new Path();
 RectF rect = new RectF(width/2 - radius, height/2 - radius, width/2 + radius, height/2 + radius);
 Matrix matrix = new Matrix();
 matrix.setScale(-1, -1, width/2, height/2);
 path.addArc(rect, 270, 270);
 path.transform(matrix);
 canvas.drawTextOnPath(msg, path, 0, 0, paint);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top