아래 이미지
<TextView
android:includeFontPadding="false"
android:background="#00ff00"
android:text="ABCD"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<NPTextView
android:includeFontPadding="false"
android:background="#00ff00"
android:text="ABCD"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
NPTextView는 1줄 짜리에만 적용해서 사용해야 합니다. 여러줄은 아직 동작 안합니다.
그리고 직접 추가한 패딩 역시 제거하기때문에 잘 사용해야 합니다.
코드 내용은 텍스트 크기를 읽어서 Rect 사이즈를 타이트하게 고정하는 내용입니다.
import android.content.Context; | |
import android.graphics.Canvas; | |
import android.graphics.Paint; | |
import android.graphics.Rect; | |
import android.support.annotation.NonNull; | |
import android.util.AttributeSet; | |
/** | |
* Created by phkim on 2017-11-24. | |
*/ | |
public class NPTextView extends android.support.v7.widget.AppCompatTextView { | |
private Paint mPaint;// = new Paint(); | |
private final Rect mBounds = new Rect(); | |
public NPTextView(Context context) { | |
super(context); | |
initPaint(); | |
} | |
public NPTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
initPaint(); | |
} | |
public NPTextView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
initPaint(); | |
} | |
private void initPaint(){ | |
mPaint = getPaint(); | |
} | |
@Override | |
protected void onDraw(@NonNull Canvas canvas) { | |
final String text = calculateTextParams(); | |
final int left = mBounds.left; | |
final int bottom = mBounds.bottom; | |
mBounds.offset(-mBounds.left, -mBounds.top); | |
mPaint.setAntiAlias(true); | |
mPaint.setColor(getCurrentTextColor()); | |
canvas.drawText(text, -left, mBounds.bottom - bottom, mPaint); | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
calculateTextParams(); | |
setMeasuredDimension(mBounds.width() + 1, -mBounds.top + 5); | |
} | |
private String calculateTextParams() { | |
final String text = getText().toString(); | |
final int textLength = text.length(); | |
mPaint.setTextSize(getTextSize()); | |
mPaint.getTextBounds(text, 0, textLength, mBounds); | |
if (textLength == 0) { | |
mBounds.right = mBounds.left; | |
} | |
return text; | |
} | |
} |