Frage

Hi I have to show progress in the number itself. I have come across Shader, Gradient used in TextView for horizontal multicoloring of the text. Is their any such built in API to paint characters as in the below image?

Sample Progress Percentage Image - MSPaint

Thanks in Advance

War es hilfreich?

Lösung

You can create two TextViews, one white and one green in exactly the same position. Set the height of one so that the text is clipped and it only partly covers the other.

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#990000" >

<TextView
    android:id="@+id/text_green"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="58dp"
    android:layout_y="77dp"
    android:text="50"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#009900"
    android:textSize="100sp" />

<TextView
    android:id="@+id/text_white"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_x="58dp"
    android:layout_y="77dp"
    android:text="50"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textColor="#FFFFFF"
    android:textSize="100sp" />

</AbsoluteLayout>

Andere Tipps

Use the below code to make gradient.

int[] color = {Color.DKGRAY,Color.CYAN};
float[] position = {0, 1};
TileMode tile_mode = TileMode.REPEAT;
LinearGradient lin_grad = new LinearGradient(0, 0, 0, 35, color, position, tile_mode);
Shader shader_gradient = lin_grad;
your_text_view.getPaint().setShader(shader_gradient); //you can change the gradient colour in textview

Another possible solution, improving on Arun's answer is this (untested but should work):

private void setTextViewShading(TextView view, float percentage) {
    int[] colors = {Color.WHITE, Color.WHITE, Color.GREEN, Color.GREEN};
    float floatPerc = percentage / 100;
    float[] position = {0, floatPerc, floatPerc + 0.0001, 1};
    TileMode tileMode = TileMode.REPEAT;
    LinearGradient linGrad = new LinearGradient(0, 0, 0, view.getHeight(), colors, position, tileMode);
    Shader shaderGradient = linGrad;
    view.getPaint().setShader(shaderGradient);
}

If I were you, I would create my own view class that, in onDraw(), renders white text using a StaticLayout, then sets a PorterDuffXferMode mask on the canvas to mask off the area you want to avoid drawing in green. Save the layer, use another StaticLayout to render the text in green then restore the layer with the mask to get the cut off exactly where you want it to be.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top