自定义一个控件,继承自ImageView
1、覆写ImageView的三个构造函数
2、覆写onDraw() 方法,利用canvas重绘想展示的界面
3、在布局文件中声明该控件,需要加上包名
在布局文件中的声明
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/line"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.android.activity.MatrixTransImageView
android:id="@+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:src="@drawable/ic_launcher"
android:gravity="center"
/>
</LinearLayout>
继承类
package com.android.activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.util.AttributeSet; import android.widget.ImageView; public class MatrixTransImageView extends ImageView { private Bitmap bitmap; private Matrix matrix; public MatrixTransImageView(Context context) { super(context); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); matrix = new Matrix(); } public MatrixTransImageView(Context context, AttributeSet attrs) { super(context,attrs); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); matrix = new Matrix(); } public MatrixTransImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); matrix = new Matrix(); } //该方法在控件显示在activity中时自动调用 @Override protected void onDraw(Canvas canvas) { //在(100,100)处显示ic_lanucher canvas.drawBitmap(bitmap, 100, 100, null); super.onDraw(canvas); } }