public void setMagnifier(Activity activity) { //一个浮层添加到R.id.content上用来触发放大功能 ImageView view = new ImageView(activity); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); view.setBackgroundColor(android.R.color.white); ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); ((ViewGroup) decorView).addView(view); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { Magnifier.Builder builder = new Magnifier.Builder(view); // builder.setOverlay(ContextCompat.getDrawable(this, R.mipmap.magnifier));//设置覆盖物 builder.setInitialZoom(2);//设置初始放大倍数,与Magnifier的setZoom功能相同 builder.setCornerRadius(300); //设置圆角:0-100 builder.setClippingEnabled(true);//false时放大镜可以滑到手机屏幕外;true时放大镜只能再屏幕内滑动。 builder.setSize(DimensionExtKt.getDp(180), DimensionExtKt.getDp(180));//设置放大镜宽高 Magnifier magnifier = builder.build(); magnifier.setZoom(2); //设置放大倍数: magnifier.show(0.0f, 0.0f); view.setOnTouchListener((v, event) -> { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: // Fall through. case MotionEvent.ACTION_MOVE: { // image.setVisibility(View.VISIBLE); final int[] viewPosition = new int[2]; v.getLocationOnScreen(viewPosition); magnifier.show(event.getRawX() - viewPosition[0], event.getRawY() - viewPosition[1]); break; } case MotionEvent.ACTION_CANCEL: // Fall through. case MotionEvent.ACTION_UP: { v.setVisibility(View.GONE); //直接移除有问题 空指针 v.postDelayed(new Runnable() { @Override public void run() { ViewGroup parent = (ViewGroup) v.getParent(); if (parent != null) { parent.removeView(v); } } }, 1000); magnifier.dismiss(); if (mFloatWindow != null) { mFloatWindow.showFloatWindow(); } } } return true; }); } } }
自定义view也可以实现放大功能 但是遇到像 surfaceview、地图这类的 拿不到具体图像 所以不能通过自定义view实现