Android 计算ImageView的大小

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;
}
 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值