1.mMagnifierView.java 自定义控件类
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
public class mMagnifierView extends ImageView {
//放大镜的半径
private static final int RADIUS = 80;
//放大倍数
private static final int FACTOR = 2;
private Matrix matrix = new Matrix();
public static final String TAG = "MagnifierView";
private Paint mPaint = new Paint();
private Bitmap mBitmap;
private Bitmap mMagnifierBitmap;
private float mPointX = -1.0f, mPointY = -1.0f;
private boolean isFirstDraw = true;
Handler mHandler = new Handler(){
public void dispatchMessage(Message msg) {
switch(msg.what){
case -1:
postInvalidate();
break;
}
};
};
public mMagnifierView(Context context, AttributeSet attrs) {
super(context, attrs);
Bitmap bImage = ((BitmapDrawable)this.getDrawable()).getBitmap();
mPaint.setAntiAlias(true);
mBitmap = bImage;
matrix.setScale(FACTOR, FACTOR);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
if (isFirstDraw) {
isFirstDraw = false;
} else {
drawMagnifierPart(canvas);
}
}
//被放大的图形
private void drawMagnifierPart(Canvas canvas){
if(mPointX == -1.0f || mPointY == -1.0f) return;
Path path = new Path();
path.addCircle(RADIUS, RADIUS, RADIUS, Direction.CW);
//底图
canvas.drawBitmap(mBitmap, 0, 0, null);
//剪切,调整放大圆的位置
canvas.translate(mPointX - RADIUS, mPointY - RADIUS);
canvas.clipPath(path);
//画放大后的图
canvas.translate(RADIUS-mPointX*FACTOR, RADIUS-mPointY*FACTOR);
canvas.drawBitmap(mBitmap, matrix, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "action move");
mPointX = event.getX();
mPointY = event.getY();
mHandler.sendEmptyMessage(-1);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mPointX = -1.0f;
mPointY = -1.0f;
mHandler.sendEmptyMessage(-1);
break;
}
return true;
}
}
2.layout/main.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"
>
<TextView
android:id="@+id/myTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
<com.xu.service.mMagnifierView android:id="@+id/theImage"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:src="@drawable/show"></com.xu.service.mMagnifierView>
</LinearLayout>
按照需要自己调整下吧