IconTextView是一个带图标的TextView,从TextView继承。
IconTextView类:
package com.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
public class IconTextView extends TextView {
private Bitmap bitmap;
public IconTextView(Context context, AttributeSet attrs) {
super(context, attrs);
int srcId = attrs.getAttributeResourceValue(null, "iconSrc", 0);
if(srcId > 0) {
bitmap = BitmapFactory.decodeResource(getResources(), srcId);
}
}
@Override
protected void onDraw(Canvas canvas) {
if(bitmap != null) {
//从原图上截取区域
Rect src = new Rect();
//目标区域
Rect target = new Rect();
src.left = 0;
src.top = 0;
src.right = bitmap.getWidth();
src.bottom= bitmap.getHeight();
int textHigh = (int)getTextSize();
target.left = 0;
target.top = (int)((getMeasuredHeight()-getTextSize())/2)+1;
target.bottom = target.top + textHigh;
target.right = (int)(textHigh * (bitmap.getWidth()/(float)bitmap.getHeight()));
canvas.drawBitmap(bitmap, src, target, getPaint());
canvas.translate(target.right+2, 0);
}
super.onDraw(canvas);
}
}
效果图:
mian.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.view.IconTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="我只能够呵呵" android:textSize="20px" iconSrc="@drawable/hehe" /> <com.view.IconTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="我只能够呵呵" android:textSize="30px" /> <com.view.IconTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="我只能够呵呵" android:textSize="40px" iconSrc="@drawable/hehe" /> <com.view.IconTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="我只能够呵呵" android:textSize="50px" iconSrc="@drawable/hehe" /> <com.view.IconTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="我只能够呵呵" android:textSize="60px" iconSrc="@drawable/hehe" /> </LinearLayout>