Search code examples
androidtextviewantialiasing

How can I rotate an Android textview with background color that is not jagged (needs to be anti-aliased)


I have a static xml layout with a background color (looks like a printed label) that I want to show at an angle. The issue I have is the edges of the background look like they were rendered in the 1980s (jagged - NOT anti-aliased).

How can I get a textview that looks like a label at an angle and have it look decent (i.e. anti-aliased)?

Layout:

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:paddingRight="5dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:includeFontPadding="false"
        android:maxLines="1"
        android:singleLine="true"
        android:text="Sample Text"
        android:textAllCaps="true"
        android:textColor="#ffffff"
        android:textSize="12sp"
        android:background="#3db8eb"
        android:rotation="-3"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"/>
</LinearLayout>

How it looks:

Example


Solution

  • After trying a few different things, I finally found something that works albeit a bit convoluted. Here's how to get smooth edges on a rotated textview with a solid color background:

    Step 1: Create a drawable resource with the color (i.e. ColorDrawable or Shape like a rectangle)

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <solid android:color="@color/blue" />
    </shape>
    

    Step 2: Set the background to that drawable.

    <TextView
      android:id="@+id/my_textview"
      ...
      android:background="@drawable/blue_rectangle" />
    

    Step 3: In code call:

    TextView textView = (TextView)findViewById(R.id.my_textview);
    textView.getBackground().setFilterBitmap(true);