Skip to content

Instantly share code, notes, and snippets.

@Reacoder
Created October 13, 2014 15:55
Show Gist options
  • Save Reacoder/26924ad8edba190dad7e to your computer and use it in GitHub Desktop.
Save Reacoder/26924ad8edba190dad7e to your computer and use it in GitHub Desktop.
TextWithUnit , upper right corner.
package com.example.zhaosam.textviewtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by zhaosam on 14-10-13.
*/
public class TextWithUnit extends TextView {
private Paint mPaint;
private float mCornerSize;
private Context mContext;
public TextWithUnit(Context context) {
super(context);
init(context);
}
public TextWithUnit(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TextWithUnit(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mContext = context;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mCornerSize = getTextSize() * 0.6f;
if (mCornerSize > 40) {
mCornerSize = 40;
}
mPaint.setTextSize(mCornerSize);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 不要忘了设置 Padding
String text = (String) getText();
Rect bounds = new Rect();
getPaint().getTextBounds(text, 0, text.length(), bounds);
canvas.drawText("%", getPaddingLeft() + bounds.right,
(canvas.getHeight() + bounds.top) / 2 + mPaint.measureText("C"),
mPaint);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment