版權(quán)聲明:本文源自簡書tianma,轉(zhuǎn)載請務(wù)必注明出處: http://www.reibang.com/p/df6deea80c2c
在ImageView中設(shè)置不同的scaleType(包括center, centerInside, centerCrop, fitXY, fitCenter, fitStart, fitEnd, matrix)屬性時,ImageView中實際的圖片(也就是Bitmap)會根據(jù)不同的scaleType屬性來確定自己相對于ImageView的位置。
例如:
-
fitCenter:
-
fitStart:
圖片中的天藍色是我給ImageView設(shè)置的backgroud屬性黎休,可以看出Bitmap相對于ImageView的位置與scaleType屬性是相關(guān)的徐钠。
那么,如何獲取Bitmap在其ImageView中的偏移量(也就是在x和y方向上的像素偏移量)呢灌旧?代碼片段如下:
/**
* 獲取Bitmap在ImageView中的偏移量數(shù)組,其中第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方向上的平移量。所以在代碼片段中會出現(xiàn):
offset[0] = (int) values[2];
offset[1] = (int) values[5];
參考鏈接:
android - how to get the image edge x/y position inside imageview
Android中圖像變換Matrix的原理逐工、代碼驗證和應(yīng)用