1. 定义属性
2. 继承View : CustomTextView.java
import android.content.Context;import android.content.res.TypedArray;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Rect;import android.util.AttributeSet;import android.util.Log;import android.widget.TextView;/** * TODO: document your custom TextView class. */public class CustomTextView extends TextView { private static final String TAG = CustomTextView.class.getSimpleName(); private Bitmap bitmap; public CustomTextView(Context context) { super(context); } public CustomTextView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.CustomizeStyle); } public CustomTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.icon_textview); int rsid = a.getResourceId(R.styleable.icon_textview_iconSrc,0); if (rsid>0) { bitmap = BitmapFactory.decodeResource(getResources(), rsid); } a.recycle(); } @Override protected void onDraw(Canvas canvas) { RectBitmap(canvas); super.onDraw(canvas); } public void RectBitmap(Canvas canvas) { if (bitmap != null) { //是否对原图片进行裁切 Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); //显示在什么地方 Rect taget = new Rect(); //起点x的坐标 taget.left=0; //起点Y的坐标:当前View的高度-字体实际占用的高度)/2 能保证图片与文字对齐 taget.top=(int)(getMeasuredHeight()-getTextSize())/2+1;// System.out.println("getMeasuredHeight:"+getMeasuredHeight());// System.out.println("getTextSize:"+getTextSize()); //保证图片等比缩放:X的坐标 taget.right = (int)(getTextSize() * (bitmap.getWidth() / (float)bitmap.getHeight())); //Y的坐标 taget.bottom= (int) (taget.top+getTextSize()); canvas.drawBitmap(bitmap, rect, taget, getPaint()); canvas.translate(taget.right+2 , 0.5f); } }}
3:布局文件