如何真正删除(AutoResize)TextView中的填充?

时间:2015-01-21 20:19:30

标签: java android android-canvas textview

上下文

我想有一个TextView,可以自动将其textize调整到屏幕的宽度。因此,我根据AutoResizeTextView下载了post by Chase。 它工作得很好,有时View仍然在设备上增长或缩小,但我可以接受。但是,我真的希望TextView的填充非常有限,以便最佳地利用屏幕上留下的空间。因此,我将课程扩展如下:

public class AutoResizeTextViewNoPadding extends AutoResizeTextView {

    public AutoResizeTextViewNoPadding(Context context) {
        super(context);
    }

    public AutoResizeTextViewNoPadding(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoResizeTextViewNoPadding(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int yOffset = getHeight() - getBaseline() - (int)super.getTextSize()/15;

        // this does not work, gives a blank view
//        int bottom = getHeight() - getBaseline() - (int)super.getTextSize()/15;
//        int top = getHeight() - bottom; // absolute number of space cut on bottom, equals top
//        canvas.clipRect(0,top,getWidth(),bottom);
//        canvas.clipRect(0, top, getWidth(), bottom, Region.Op.REPLACE);
//        super.onDraw(canvas);

        // this does not work, also gives a blank view
//        Bitmap bitmap= Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight() - 2*yOffset, Bitmap.Config.ARGB_8888);
//        Paint p = getPaint();
//        Canvas othercanvas = new Canvas();
//        othercanvas.drawBitmap(bitmap,0,0,p);
//        super.onDraw(othercanvas);

        // this works to remove the FontPadding on the bottom, but then the top gets more Padding of course
        canvas.translate(0, yOffset);
        super.onDraw(canvas);

    }
}

问题

canvas.translate将实际文本移动到视图的底部(yOffset)。但我实际上希望从视图的底部和顶部裁剪此数量(yOffset)。正如在代码中所看到的,我尝试了两件都不起作用的东西,即我看到一个空视图,其大小与普通(AutoResize)TextView相同。可以这样做吗?

或者可以用另一种方式解决这个问题吗?请注意,设置负边距将不起作用,因为文本大小范围显着,因此边距也必须是范围。或者我可以在(AutoResize)TextView(NoPadding)类中的某处设置边距吗?

1 个答案:

答案 0 :(得分:0)

它并不完美,但是如果有人在寻找相同的东西,这或多或少都是这样的(对于Android的AutoResizableTextViews:singleLine =" true"):

public class AutoResizeTextViewNoPadding extends TextView
{
(...)
        @Override
        public int onTestSize(final int suggestedSize,final RectF availableSPace)
        {
            paint.setTextSize(suggestedSize);
            final String text=getText().toString();
            final boolean singleline=getMaxLines()==1;
            if(singleline)
            {
                textRect.bottom=(float)(paint.getFontSpacing()*.8);
                textRect.right=paint.measureText(text);
            }
        (...)
        }

@Override
protected void onDraw(Canvas canvas) {
    int yOffset = getHeight() - getBaseline() - (int)super.getTextSize()/20;
    canvas.translate(0, 2*yOffset);
    super.onDraw(canvas);
}

}