Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It doesn't appear possible to extend TextView to draw text with a gradient. It is, however, possible to achieve this effect by creating a canvas and drawing on it. First we need to <a href="https://stackoverflow.com/questions/2695646/declaring-a-custom-android-ui-element-using-xml">declare our custom UI element</a>. In the initiation we need to create a subclass of <a href="http://developer.android.com/reference/android/text/Layout.html#draw%28android.graphics.Canvas%29" rel="nofollow noreferrer">Layout</a>. In this case, we will use <a href="http://developer.android.com/reference/android/text/BoringLayout.html" rel="nofollow noreferrer">BoringLayout</a> which only supports text with a single line.</p> <pre><code>Shader textShader=new LinearGradient(0, 0, 0, 20, new int[]{bottom,top}, new float[]{0, 1}, TileMode.CLAMP);//Assumes bottom and top are colors defined above textPaint.setTextSize(textSize); textPaint.setShader(textShader); BoringLayout.Metrics boringMetrics=BoringLayout.isBoring(text, textPaint); boringLayout=new BoringLayout(text, textPaint, 0, Layout.Alignment.ALIGN_CENTER, 0.0f, 0.0f, boringMetrics, false); </code></pre> <p>We then override <code>onMeasure</code> and <code>onDraw</code>:</p> <pre><code>@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ setMeasuredDimension((int) textPaint.measureText(text), (int) textPaint.getFontSpacing()); } @Override protected void onDraw(Canvas canvas){ super.onDraw(canvas); boringLayout.draw(canvas); } </code></pre> <p>Our implementation of <code>onDraw</code> is at this point quite lazy (it completely ignores the measurement specs!, but so long as you guarantee that the view is given sufficent space, it should work okay.</p> <p>Alternatively, it would be possible to inherit from a <code>Canvas</code> and override the <code>onPaint</code> method. If this is done, then unfortunately the anchor for text being drawn will always be on the bottom so we have to add <code>-textPaint.getFontMetricsInt().ascent()</code> to our y coordinate.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload