android imageview bitmap 位于底部,Android获取Bitmap在其ImageView中的偏移量

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

例如:

fitCenter:

df6deea80c2c

fitStart:

df6deea80c2c

图片中的天蓝色是我给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_X,MTRANS_Y字段分别表示x和y方向上的平移量。所以在代码片段中会出现:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值