Apr 29, 2012

Draw text along path

To draw text along path, we can call Canvas.drawTextOnPath(text, path, hOffset, vOffset, paint).

Draw text along path

Example:
Create a new class MyView extends View. Override the onDraw(Canvas canvas) method calling Canvas.drawTextOnPath() to draw text along path.
package com.AndroidMyCanvas;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

 public MyView(Context context) {
  super(context);
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
 }

 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);
  Paint paint = new Paint();
  paint.setStyle(Paint.Style.STROKE);
  paint.setColor(Color.WHITE);
  paint.setStrokeWidth(3);
  
  Path path = new Path();
  path.moveTo(50, 50);
  path.cubicTo(500, 100, 100, 500, 1000, 500);
  canvas.drawPath(path, paint);
  canvas.drawPath(path, paint);
  
  paint.setStyle(Paint.Style.FILL_AND_STROKE);
  paint.setTextSize(100);
  
  //drawTextOnPath(text, path, hOffset, vOffset, paint)
  paint.setColor(Color.GRAY);
  canvas.drawTextOnPath("--- Android.Coding ---", path, 110, 5, paint);
  paint.setColor(Color.GREEN);
  canvas.drawTextOnPath("--- Android.Coding ---", path, 100, 0, paint);
 }

}


Modify main Java activity to setContentView() using our custom View, MyView.
package com.AndroidMyCanvas;

import android.app.Activity;
import android.os.Bundle;

public class AndroidMyCanvasActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
}


No comments:

Post a Comment

Infolinks In Text Ads