步骤:
1、在values下新建一个attrs.xml的资源文件(my_attrs.xml)
<declare-styleable name="My_attrs"> //===》name为引用资源的名称
// attr中的 name为自定义的名称 format 为类型
<attr name="TextColor" format="color"></attr> // 字体颜色
<attr name="TextSize" format="dimension"></attr> //字体大小
<attr name="Text" format="string"></attr> //字符串
</declare-styleable>
2、新建一个类MyAttrsMyView继承 View
覆写public MyAttrsMyView(Context context, AttributeSet attrs)方法
@SuppressLint("NewApi")
public MyAttrsMyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mPaint = new Paint(); //定义画笔
imageView = new ImageView(context); //图片
imageView.setImageResource(R.drawable.ww); //加载图片资源
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.My_attrs); //获取自定义的attrs中的资源
float textsize = a.getDimension(R.styleable.My_attrs_TextSize, 40);
int c = a.getColor(R.styleable.My_attrs_TextColor, 0x990000FF);
s = a.getString(R.styleable.My_attrs_Text);
mPaint.setColor(c);
mPaint.setTextSize(textsize);
a.recycle(); //结束标记
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//canvas.drawRect(new Rect(10, 10, 280, 200), mPaint);
//((BitmapDrawable)imageView.getDrawable()).getBitmap() ;将imageview转换成bitmap
canvas.drawBitmap(((BitmapDrawable)imageView.getDrawable()).getBitmap(), 1, 20, mPaint);
//canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ww), 10, 10, mPaint);
canvas.drawText(s, 1, 100, mPaint);
}
3、最后一步
第一种写法 在activity中 , 直接new出自定义的类即可
MyView = new MyAttrsMyView(this,null);
setContentView(MyView);
第二种写法 利用xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ymy="http://schemas.android.com/apk/res/com.ming"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.ming.attrs.MyAttrsMyView
android:layout_width="400dp"
android:layout_height="300dp"
ymy:TextColor = "#ABCDEFEF"
ymy:Text = "顺丰快递"
ymy:TextSize = "12sp"
/>
</LinearLayout>