Android 图片与屏幕坐标点

计算获取的ImageView图片显示时的实际大小(ps:这里会用到可见ImageView的宽高主要是因为我需要根据可见ImageView的宽高来设置其他控件的宽高,还有就是后面关于图像与屏幕坐标点的转换会需要用到)

 private void setLayoutParams() {
        int[] size = ImageUtils.getRealImgShowSize(mImageView);
        mRealImgShowWidth = size[0];
        mRealImgShowHeight = size[1];
        ViewGroup.LayoutParams params = mImageView.getLayoutParams();
        params.height = mRealImgShowHeight;
        params.width = mRealImgShowWidth;
        mImageView.setLayoutParams(params);       
    }
   //0:宽 1:高
  public static int[] getRealImgShowSize(ImageView imageview){
        Rect rect=imageview.getDrawable().getBounds();
        //可见image的宽高
        int scaledHeight = rect.height();
        int scaledWidth = rect.width();
        //获得ImageView中Image的变换矩阵
        Matrix matrix= imageview.getImageMatrix();
        float[] values = new float[10];
        matrix.getValues(values);
        //Image在绘制过程中的变换矩阵,从中获得x和y方向的缩放系数
        float sx = values[0];
        float sy = values[4];
        //计算Image在屏幕上实际绘制的宽高
       int realImgShowWidth =(int) (scaledWidth * sx);
       int realImgShowHeight =(int)( scaledHeight * sy);
       int[] size=new int[]{realImgShowWidth,realImgShowHeight};
        return size;
    }
//屏幕坐标转图片坐标
    private List getBitmapPoints(Bitmap original, Map points) {
        List srccorners = new ArrayList<>();

        float xRatio = (float) original.getWidth() /mRealImgShowWidth;//mRealImgShowWidth=ImageView.getWidth()
        float yRatio = (float) original.getHeight() / mRealImgShowHeight;

        float x1 = (points.get(0).x) * xRatio;
        float x2 = (points.get(1).x) * xRatio;
        float x3 = (points.get(2).x) * xRatio;
        float x4 = (points.get(3).x) * xRatio;
        float y1 = (points.get(0).y) * yRatio;
        float y2 = (points.get(1).y) * yRatio;
        float y3 = (points.get(2).y) * yRatio;
        float y4 = (points.get(3).y) * yRatio;
        srccorners.add(new Point(x1, y1));
        srccorners.add(new Point(x2, y2));
        srccorners.add(new Point(x3, y3));
        srccorners.add(new Point(x4, y4));
        return srccorners;
    }
    //图片坐标转屏幕坐标
    private  Map getScreenPoints(Bitmap original,Map points){
        float xRatio = (float) original.getWidth() / mRealImgShowWidth;
        float yRatio = (float) original.getHeight() / mRealImgShowHeight;
       Map screenPoints=new HashMap<>();
        float x1 = points.get(0).x/xRatio;
        float x2 = points.get(1).x / xRatio;
        float x3 = points.get(2).x / xRatio;
        float x4 =points.get(3).x / xRatio;
        float y1 =  points.get(0).y / yRatio;
        float y2 =  points.get(1).y/ yRatio;
        float y3 = points.get(2).y/ yRatio;
        float y4 =  points.get(3).y / yRatio;
        screenPoints.put(0,new PointF(x1,y1));
        screenPoints.put(1,new PointF(x2,y2));
        screenPoints.put(2,new PointF(x3,y3));
        screenPoints.put(3,new PointF(x4,y4));
        return screenPoints;
    }

你可能感兴趣的:(Android)