Android获取Bitmap在其ImageView中的偏移量

版权声明:本文源自tianma,转载请务必注明出处: http://www.jianshu.com/p/df6deea80c2c

在ImageView中设置不同的scaleType(包括center, centerInside, centerCrop, fitXY, fitCenter, fitStart, fitEnd, matrix)属性时,ImageView中实际的图片(也就是Bitmap)会根据不同的scaleType属性来确定自己相对于ImageView的位置。
例如:

  • fitCenter:


  • fitStart:


    Android获取Bitmap在其ImageView中的偏移量_第1张图片

    图片中的天蓝色是我给ImageView设置的backgroud属性,可以看出Bitmap相对于ImageView的位置与scaleType属性是相关的。
    那么,如何获取Bitmap在其ImageView中的偏移量(也就是在x和y方向上的像素偏移量)呢?代码片段如下:

    /**
     * 获取Bitmap在ImageView中的偏移量数组,其中第0个值表示在水平方向上的偏移值,第1个值表示在垂直方向上的偏移值
     *
     * @param imageView
     * @param includeLayout 在计算偏移的时候是否要考虑到布局的因素,如果要考虑该因素则为true,否则为false
     * @return the offsets of the bitmap inside the imageview, offset[0] means horizontal offset, offset[1] means vertical offset
     */
    private int[] getBitmapOffset(ImageView imageView, boolean includeLayout) {
        int[] offset = new int[2];
        float[] values = new float[9];

        Matrix matrix = imageView.getImageMatrix();
        matrix.getValues(values);

        // x方向上的偏移量(单位px)
        offset[0] = (int) values[2];
        // y方向上的偏移量(单位px)
        offset[1] = (int) values[5];

        if (includeLayout) {
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) imageView.getLayoutParams();
            int paddingTop = imageView.getPaddingTop();
            int paddingLeft = imageView.getPaddingLeft();

            offset[0] += paddingLeft + params.leftMargin;
            offset[1] += paddingTop + params.topMargin;
        }
        return offset;
    }

上面的代码中Matrix类实际上是一个3*3的矩阵,看Android源码:

public class Matrix {
    public static final int MSCALE_X = 0; 
    public static final int MSKEW_X  = 1;
    public static final int MTRANS_X = 2;
    public static final int MSKEW_Y  = 3;
    public static final int MSCALE_Y = 4;
    public static final int MTRANS_Y = 5;
    public static final int MPERSP_0 = 6;
    public static final int MPERSP_1 = 7;
    public static final int MPERSP_2 = 8;
    ...
}

其中MTRANS_XMTRANS_Y字段分别表示x和y方向上的平移量。所以在代码片段中会出现:

offset[0] = (int) values[2];
offset[1] = (int) values[5];

参考链接:
android - how to get the image edge x/y position inside imageview
Android中图像变换Matrix的原理、代码验证和应用

你可能感兴趣的:(Android获取Bitmap在其ImageView中的偏移量)