3

I have one image and on that i have to write top and bottom text, i am using static layout to write on it. Below is the code of it

TextPaint mTextPaintTop= new TextPaint();
mTextPaintTop.setColor(Color.RED);
StaticLayout layoutTop = new StaticLayout(top_text, mTextPaintTop,             
width,Layout.Alignment.ALIGN_CENTER, 1.3f, 0, false);
canvas.translate(0, 20); //position the text
layoutTop.draw(canvas);

I want to restrict the text up to two lines. If user types long text and if it goes beyond 2 line, then reduce font size, so that it can be adjusted to 2 lines only.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
moDev
  • 5,248
  • 4
  • 33
  • 63

1 Answers1

0

Download this file EllipsizingTextView

@Override
    public void draw(Canvas canvas) {
    // TODO Auto-generated method stub

    Paint mpaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    mpaint.setColor(Color.RED);

    mpaint.setTextSize(13);

    mpaint.setTextAlign(Align.CENTER);

        drawTextOnCanvas(canvas, "text you want 2 line bigger", 0, 20, mpaint);

    }

}

private void drawTextOnCanvas(Canvas canvas, String text, int x, int y, Paint mPaint) {
        // Setup a textview like you normally would with your activity context
        EllipsizingTextView tv = new EllipsizingTextView(mContext);

        tv.setGravity(Gravity.CENTER_HORIZONTAL);
        tv.setEllipsize(TruncateAt.END);
        tv.setMaxLines(2);
        // setup text
        tv.setText(text);

        // maybe set textcolor
        tv.setTextColor(Color.WHITE);

        // you have to enable setDrawingCacheEnabled, or the getDrawingCache will return null
        tv.setDrawingCacheEnabled(true);

        // we need to setup how big the view should be..which is exactly as big as the canvas
        tv.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));

        // assign the layout values to the textview
        tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());

        // draw the bitmap from the drawingcache to the canvas
        canvas.drawBitmap(tv.getDrawingCache(), x, y, mPaint);

        // disable drawing cache
        tv.setDrawingCacheEnabled(false);
    }
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115