Miljan Vulovic Miljan Vulovic - 18 days ago 7
Android Question

Drawable inside text as background

I want to achieve this:

enter image description here

I created a TextDrawable class and I have drawn a text. But how do I fill it with the drawable that I have?

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;

public class TextDrawable extends Drawable {
private static final int DEFAULT_COLOR = Color.WHITE;
private static final int DEFAULT_TEXTSIZE = 45;
private Paint mPaint;
private CharSequence mText;
private int mIntrinsicWidth;
private int mIntrinsicHeight;

public TextDrawable(Resources res, CharSequence text) {
mText = text;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.RED);
mPaint.setTextAlign(Align.CENTER);
mPaint.setStrokeWidth(5);
float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_TEXTSIZE, res.getDisplayMetrics());
mPaint.setTextSize(textSize);
mIntrinsicWidth = (int) (mPaint.measureText(mText, 0, mText.length()) + .5);
mIntrinsicHeight = mPaint.getFontMetricsInt(null);
}

@Override
public void draw(Canvas canvas) {
Rect bounds = getBounds();
canvas.drawText(mText, 0, mText.length(), bounds.centerX() + 15, bounds.centerY() + 15, mPaint);
}

@Override
public int getOpacity() {
return mPaint.getAlpha();
}

@Override
public int getIntrinsicWidth() {
return mIntrinsicWidth;
}

@Override
public int getIntrinsicHeight() {
return mIntrinsicHeight;
}

@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}

@Override
public void setColorFilter(ColorFilter filter) {
mPaint.setColorFilter(filter);
}

}


Drawable gradient:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:color="@color/night_blue"
tools:targetApi="lollipop">
<item android:id="@android:id/background">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<gradient
android:angle="0"
android:endColor="@color/color_end"
android:startColor="@color/color_start" />


</shape>
</item>
</ripple>


The ripple effect can go if necessary, but, I need to be able to draw text with the fill like this image.

Answer

Use it like this:

        mPaint.setShader(new LinearGradient(0, 0, 0, mIntrinsicHeight, res.getColor(R.color.color_start), res.getColor(R.color.color_end), Shader.TileMode.CLAMP));
Comments