Java代碼
package com.myself.custom.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;
import com.myself.custom.activity.R;
/**
* @檔案名 IconTextView.java
* @類說明 (帶圖檔的TextView)
* @作者 xxxx
* @版本 v_1.0
* @建立時間 2014-3-19 下午12:06:50
*/
public class IconTextView extends TextView {
private final String ATTR_ICON_SRC = "iconSrc";
private final String NAMESPACE = "http://www.myself.com";
private Bitmap bitMap;
public IconTextView(Context context, AttributeSet attrs) {
super(context, attrs);
int resouceId = attrs.getAttributeResourceValue(NAMESPACE, ATTR_ICON_SRC, R.drawable.ic_launcher);
bitMap = BitmapFactory.decodeResource(getResources(), resouceId);
}
@Override
protected void onDraw(Canvas canvas) {
if(bitMap != null){
//源 将圖像截取部分内容,這裡為整張圖像
Rect src = new Rect();
src.top = 0;
src.left = 0;
src.right = bitMap.getWidth();
src.bottom = bitMap.getHeight();
int textHeight = (int) getTextSize();
Rect target = new Rect();
target.left = 0;
// 計算圖像複制到目錄區域的縱坐标。由于TextView中文本内容并不是從最頂端開始繪制的,是以,需要重新計算繪制圖像的縱坐标
target.top = (int) ((getMeasuredHeight() - getTextSize()) / 2) + 1;
target.bottom = target.top + textHeight;
// 為了保證圖像不變形,需要根據圖像高度重新計算圖像的寬度
target.right = (int) (textHeight * (bitMap.getWidth() / (float) bitMap
.getHeight()));
canvas.drawBitmap(bitMap, src, target, getPaint());
canvas.translate(target.right + 2, 0);
}
super.onDraw(canvas);
}
}
xml引用方式
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myself="http://www.myself.com"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.myself.custom.view.IconTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
myself:iconSrc="@drawable/ic_menu_shuffle"
android:text="我是textView"
android:textSize="30sp"
/>
</LinearLayout>