记录学习自定义view过程
1.主体代码
public class ZoomImageView extends View {
//放大倍数
private static final int FACTOR =2;
//放大镜的半径
private static final int RADIUS = 50;
// 原图
private Bitmap mBitmap;
// 放大后的图
private Bitmap mBitmapScale;
// 制作的圆形的图片(放大的局部),盖在Canvas上面
private ShapeDrawable mShapeDrawable;
private Matrix mMatrix;
public ZoomImageView(Context context,@Nullable AttributeSet attrs) {
super(context,attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 画放大镜的图
mShapeDrawable.draw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获取父容器给设置的测量模式和大小
//在设置wrap_content时候,重新测量view的大小
int iWidthMode = MeasureSpec.getMode(widthMeasureSpec);
int iHeightMode = MeasureSpec.getMode(heightMeasureSpec);
int iWidthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int iHeightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int measuredWith;
int measuredHeight;
mBitmap =((BitmapDrawable)getBackground()).getBitmap();
//这里只处理了都设置为wrap_content的情况,若有其他,可以增加判断,
if (iWidthMode == MeasureSpec.EXACTLY && iHeightMode == MeasureSpec.EXACTLY) {
measuredWith = iWidthSpecSize;
measuredHeight = iHeightSpecSize;
}else {
measuredWith=mBitmap.getWidth();
measuredHeight = mBitmap.getHeight();
}
setMeasuredDimension(measuredWith,measuredHeight);
//放大后的整个图片
mBitmapScale = Bitmap.createScaledBitmap(mBitmap,measuredWith * FACTOR,
measuredHeight * FACTOR,true);
BitmapShader bitmapShader = new BitmapShader(mBitmapScale, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
mShapeDrawable = new ShapeDrawable(new OvalShape());
mShapeDrawable.getPaint().setShader(bitmapShader);
// 切出矩形区域,用来画圆(内切圆)
mShapeDrawable.setBounds(0,0,RADIUS * 2,RADIUS * 2);
mMatrix = new Matrix();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
// 将放大的图片往相反的方向挪动
mMatrix.setTranslate(RADIUS - x * FACTOR, RADIUS - y *FACTOR);
mShapeDrawable.getPaint().getShader().setLocalMatrix(mMatrix);
// 切出手势区域点位置的圆
mShapeDrawable.setBounds(x-RADIUS,y - RADIUS, x + RADIUS, y + RADIUS);
invalidate();
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:lpq="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cccccc"
android:orientation="vertical">
<com.example.lpq.myapplication.customview.ZoomImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/s"/>
</LinearLayout>