package com.example.jinzhe.shapeviewdemo; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Path; import android.view.MotionEvent; import android.view.View; /** * Created by jinzhe on 2016/8/2. */ public class ShaderView extends View{ private Path mPath = new Path(); private Matrix matrix = new Matrix(); private Bitmap bitmap; //放大镜的半径 private static final int RADIUS = 80; //放大倍数 private static final int FACTOR = 2; private int mCurrentX, mCurrentY; public ShaderView(Context context) { super(context); mPath.addCircle(150, 150, RADIUS, Path.Direction.CW); matrix.setScale(FACTOR, FACTOR); bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.demo); } @Override public boolean onTouchEvent(MotionEvent event) { mCurrentX = (int) event.getX(); mCurrentY = (int) event.getY(); invalidate(); return true; } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); //底图 canvas.drawBitmap(bitmap, 0, 0, null); //剪切 //改变画布的原点位置 canvas.translate(mCurrentX - RADIUS, mCurrentY - RADIUS); canvas.clipPath(mPath); //画放大后的图 canvas.translate(RADIUS-mCurrentX*FACTOR, RADIUS-mCurrentY*FACTOR); canvas.drawBitmap(bitmap, matrix, null); } }
在Activity中的设置
package com.example.jinzhe.shapeviewdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams .MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); ShaderView view = new ShaderView(getBaseContext()); //是某一个构造函数的上下文 addContentView(view, params); } }