0

i have created a custom view but am facing difficulties in positioning at center of screen.

public class CurvedText extends View {
    private static final String MY_TEXT = "Select A Mode";
    private Path mArc;

    private Paint mPaintText;

    public CurvedText(Context context, AttributeSet attrs) {
      super(context, attrs);     


      mArc = new Path();
      RectF oval = new RectF(0,0,200,200);
      mArc.addArc(oval, -45, 200);          
      mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
      mPaintText.setStyle(Paint.Style.FILL_AND_STROKE);
      mPaintText.setColor(Color.WHITE);
      mPaintText.setTextSize(20f);

    }

    @Override
    protected void onDraw(Canvas canvas) {
      canvas.drawTextOnPath(MY_TEXT, mArc, 0, 10, mPaintText);      
      invalidate();
    }


  }

I know i can workaround using setting RectF coordinates but i want this text at center of screen. SO how can i dynamically get the coordinates of the center of the screen? or any other way to position it at the center of the screen.

Adding Declaration:

<com.pkg.CurvedText
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:gravity="center" >
</com.pkg.CurvedText>
Mercurial
  • 3,615
  • 5
  • 27
  • 52

1 Answers1

0
 private static int [] screenDimens;

 /**
 * Gets the width and height of the screen. If null is passed, this method returns the previously
 * requested parameters.
 *
 * @param activity {@link android.app.Activity}
 * @return int [0] = width, int[1] = height
 */
public static int [] getScreenDimensInPx(Activity activity) {
    if(activity != null) {
        Display display = activity.getWindowManager().getDefaultDisplay();

        Point size = new Point();
        display.getSize(size);

        int width = size.x;
        int height = size.y;

        screenDimens = new int[]{width, height};
    }

    return screenDimens;
}

That should get you the width and height of the screen. The centre of the screen is simply width/2 and height/2. OF course, you need a reference to an Activity to do this.

Here's how i'm using the code I showed you. In my project I have a Utilities class that contains only public static methods. In that class, I keep a private static reference to an int array that holds these dimensions. Whenever the public static function with the above code is called, I simply populate the private static int array. Mind you, the function accepts an Activity to be able to get the values. In the method, I check whether the passed in Activity is null. If it is null, I simply return the value of the private static int array. This way, I can call this method one time when my app starts (from any Activity), and store those values. Then, later if I need those values again, I simply call the same method but with a null parameter, and I get my stored values back. Hope this makes sense!

The Hungry Androider
  • 2,274
  • 5
  • 27
  • 52