package com.example.myapi.pictobig;import com.example.myapi.R;import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Shader.TileMode; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; /** * 图片放大镜工具类 * @author yw-tony * */ public class PicToBigTools extends ImageView{ private Bitmap bitmap; private ShapeDrawable drawable; /*放大镜的半径*/ private static final int RADIUS = 80; /*放大倍数*/ private static final int FACTOR = 3; private Matrix matrix = new Matrix(); /** * 构造方法 * @param context */ public PicToBigTools(Context context) { super(context); Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pictobig_icon); bitmap = bmp; BitmapShader shader = new BitmapShader( Bitmap.createScaledBitmap(bmp, bmp.getWidth()*FACTOR, bmp.getHeight()*FACTOR, true), TileMode.CLAMP, TileMode.CLAMP); //圆形的drawable drawable = new ShapeDrawable(new OvalShape()); drawable.getPaint().setShader(shader); /*设置放大的区域*/ drawable.setBounds(0, 0, RADIUS*2, RADIUS*2); } @Override public boolean onTouchEvent(MotionEvent event) { final int x = (int) event.getX(); final int y = (int) event.getY(); /**设置图片等比例缩放*/ // 获得图片的宽高 int width = bitmap.getWidth(); int height = bitmap.getHeight(); // 计算缩放比例 float scaleWidth = ((float) RADIUS*2) / width; float scaleHeight = ((float) RADIUS*2) / height; matrix.postScale(scaleWidth,scaleHeight); //这个位置表示的是,画shader的起始位置 matrix.setTranslate(RADIUS-x*FACTOR, RADIUS-y*FACTOR); drawable.getPaint().getShader().setLocalMatrix(matrix); //bounds,就是那个圆的外切矩形 drawable.setBounds(x-RADIUS, y-RADIUS, x+RADIUS, y+RADIUS); invalidate();//更新UI return true; } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(bitmap, 0, 0, null); drawable.draw(canvas);//绘制图片 } }