Search code examples
androidnine-patch

how stretch inside a circle image with nine patch


I have a image that is as a circle .I want stretch only part of inside of it and i dont want stretch borders of it. as example my image is same below

enter image description here

I set it as backgrount my textview.i want if text is large it stretch as a circle and text place in center black circle .


Solution

  • It may not be possible with using the 9-patch images. However I think your requirement can be achieved by using shape drawables. Following are the sample code which you can refer:

    1. Create two circular shapes (outer_circle.xml and inner_circle.xml) in drawable folder.
    2. Place the textview inside a LinearLayout where layout background is outer circle and text background is inner circle.
    3. Programmatically update the height of textview to make it equal with the width.

    Following is the code:

    1. outer_circle.xml

    <solid android:color="#ffffff" />
    
    <stroke
        android:width="10dp"
        android:color="#000000" />
    
    <size
        android:height="120dp"
        android:width="120dp" />
    

    2.inner_circle.xml

    <!-- Give the padding so the text does not touches the edge of inner circle -->
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
    
    <solid android:color="#000000" />
    

    3.Layout Sample

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/outer_circle"
        android:gravity="center" >
    
        <TextView
            android:id="@+id/textTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/inner_circle"
            android:gravity="center"
            android:text="Test"
            android:textColor="#aaaaaa"
            android:textStyle="bold" />
    </LinearLayout>
    

    4.Set the textView layout programmatically

    // Override this method to get the text width dynamically and 
    // apply the same height to the textview
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
    
        super.onWindowFocusChanged(hasFocus);
        TextView tvTest = (TextView) findViewById(R.id.textTest);
        int tvWidth = tvTest.getWidth();
        ViewGroup.LayoutParams tvLayout = tvTest.getLayoutParams();
        tvLayout.height = tvLayout.width = tvWidth;
        tvTest.setLayoutParams(tvLayout);
    
    }
    

    Following is the part of screenshot

    enter image description here

    Alternatively you can have a look into this links

    How to draw a smaller ShapeDrawable inside another shapeDrawable programmatically

    Hope this will be useful.