1.获取资源文件中图片的大小,最简单的最直接的方法,就是使用Drawable的getIntrinsicHeight()和getIntrinsicWidth();
2.利用Bitmap来获取其大小,本质上和第一种方式没什么区别:
/**
* 计算ImageView的大小(BitmapDrawable)
*
* @param resources
* @param resourceId
* @return
*/
public static int[] computeWH(Resources resources, int resourceId) {
int[] wh = { 0, 0 };
if (resources == null)
return wh;
Bitmap mBitmap = BitmapFactory.decodeResource(resources, resourceId);
BitmapDrawable bDrawable = new BitmapDrawable(resources, mBitmap);
wh[0] = bDrawable.getIntrinsicWidth();
wh[1] = bDrawable.getIntrinsicHeight();
return wh;
}
3.可以利用BitmapFactory.Options的outWidth和outHeight两个参数获取其大小,下面给出简单的3种方法供参考:
注意:设置inJustDecodeBounds为true后,decodeFile并不分配空间,即,BitmapFactory解码出来的Bitmap为Null,但可计算出原始图片的长度和宽度。
/**
* 计算ImageView的大小(decodeFileDescriptor)
*
* @param imageFile
* @return
*/
public static int[] computeWH_1(String imageFile) {
int[] wh = { 0, 0 };
if (imageFile == null || imageFile.length() == 0)
return wh;
try {
FileDescriptor fd = new FileInputStream(imageFile).getFD();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd, null, options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return wh;
}
wh[0] = options.outWidth;
wh[1] = options.outHeight;
} catch (Exception e) {
}
return wh;
}
/**
* 计算ImageView的大小(decodeFile)
*
* @param imgFile
* @return
*/
public static int[] computeWH_2(String imgFile) {
int[] wh = { 0, 0 };
if (imgFile == null || imgFile.length() == 0)
return wh;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgFile, options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return wh;
}
wh[0] = options.outWidth;
wh[1] = options.outHeight;
return wh;
}
/**
* 计算ImageView的大小(decodeResource)
*
* @param resources
* @param resourceId
* @return
*/
public static int[] computeWH_3(Resources resources, int resourceId) {
int[] wh = { 0, 0 };
if (resources == null)
return wh;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resourceId, options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return wh;
}
wh[0] = options.outWidth;
wh[1] = options.outHeight;
return wh;
}