自定义TextView在上面加个小图片

package mydraw.com.mydraw;

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;

/**
 * Created by dream on 2015/11/15.
 */
public class MyTextView extends TextView {

    private Bitmap bitmap;
    //图像资源ID的变量
    private int resourceId =0;
    private final String namespace =  "http://net.blogjava.mobile";//命名空间

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
         /*这里取得declare-styleable集合*/
       // TypedArray typeArray = context.obtainStyledAttributes(attrs,R.styleable.MyTextView);

        resourceId = attrs.getAttributeResourceValue(namespace, "iconSrc", 0);
        bitmap = BitmapFactory.decodeResource(getResources(),resourceId);
    }


    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(bitmap == null){
            return;
        }
        int textHeight = (int) getTextSize();

        /***画bitmap的小区域******/
        Rect src = new Rect();
        src.left = bitmap.getWidth()/2;
        src.top = bitmap.getHeight()/2;
        src.right = bitmap.getWidth();
        src.bottom = bitmap.getHeight();
        /***将画好的图放置在屏幕上的区域**/
        Rect target = new Rect();
        target.left=getMeasuredWidth()/2;
        target.top=0;
        target.right=getMeasuredWidth();
        target.bottom=getMeasuredHeight();
        canvas.drawBitmap(bitmap,src,target,getPaint());
        super.onDraw(canvas);
    }
}

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:modbile="http://net.blogjava.mobile"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
 >
    <mydraw.com.mydraw.MyTextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        modbile:iconSrc="@drawable/cat2"/>

</RelativeLayout>

参考:http://www.cnblogs.com/lonelyDog/archive/2012/06/28/2568519.html


你可能感兴趣的:(自定义TextView在上面加个小图片)