Android 本地图片 设置成宽高固定的背景

在Android开发中,为了将从手机图库获取的图片设置为宽高固定的背景,需要自定义适配器并重写`setViewImage()`方法。通过使用自定义的`getImageThumbnail()`函数,可以实现将任意图片地址转换为适应背景尺寸的缩略图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:先获得图片的地址:

访问收手机图库:

	Intent intent= new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);            
				 startActivityForResult(intent, RESULT_LOAD_IMAGE);

获取地址并显示在ImageView中:
@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	 
	    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
	        Uri selectedImage = data.getData();
	        String[] filePathColumn = { MediaStore.Images.Media.DATA };
	 
	        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
	        cursor.moveToFirst();
	 
	        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	        selectPicturePath = cursor.getString(columnIndex);
	        cursor.close();
	 
	        // String picturePath contains the path of selected Image
	        ImageView imageView = new ImageView(NewNoticeActivity.this);
	        LayoutParams lp =new LinearLayout.LayoutParams(150,150);
	        lp.rightMargin=20;
	        imageView.setLayoutParams(lp);
            imageView.setBackgroundResource(R.drawable.border_grey2);
            imageView.setPadding(2, 2, 2, 2);
            imageView.setImageBitmap(Common.getImageThumbnail(selectPicturePath, 150, 150));
            int index=ll_img.getChildCount();
            ll_img.addView(imageView, index-1);
	}
	}
效果图:



如果是在listview中显示,先自定义适配器,正常SimpleAdapter可以放图片,但是只能是drawable里面固定图片,如果是手机图库里任意一张图片,或者网络上这些不固定地址的图片就不行了。所以要自定义adapter继承SimpleAdapter。重写里面的setViewImage(ImageView v, String value){}函数。代码如下:

public class NewsListAdapter extends SimpleAdapter {
	Context context;

	public NewsListAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
		super(context, data, resource, from, to);
		this.context = context;
	}

	// set the imageView using the path of image
	public void setViewImage(ImageView v, int value) {
		v.setImageResource(value);
	}

	@SuppressLint("NewApi")
	public void setViewImage(ImageView v, String value) {
//		LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 200);
//		v.setLayoutParams(lp);
		int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        v.measure(w, h);
        int width =v.getMeasuredWidth();
        int height =v.getMeasuredHeight();
		System.out.println("---tupian :  "+width+" ,  "+ height);
		v.setImageBitmap(Common.getImageThumbnail(value, width, height));
		// try {
		// Bitmap bitmap = BitmapFactory.decodeFile(value);
		// Bitmap newBit = Bitmap.createScaledBitmap(bitmap,
		// v.getLayoutParams().width, v.getLayoutParams().height, true);
		// v.setImageBitmap(newBit);
		// } catch (NumberFormatException nfe) {
		// v.setImageURI(Uri.parse(value));
		// }
	}

}

注:LayoutParams貌似只能设置宽高,不能获取宽高,获取的宽高都是0或者-2,不准确。如果是获取宽高,还是用getMeasuredWidth()和getMeasuredHeight();

效果图:


最后关于Common.getImageThumbnail()函数:

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处: 1.
     * 使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度,
     * 第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使 用这个工具生成的图像不会被拉伸。
     * @param imagePath 图像的路径
     * @param width 指定输出图像的宽度
     * @param height 指定输出图像的高度
     * @return 生成的缩略图
     */
    public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高,注意此处的bitmap为null
        try
        {
            bitmap = BitmapFactory.decodeFile(imagePath, options);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight)
        {
            be = beWidth;
        } else
        {
            be = beHeight;
        }
        if (be <= 0)
        {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值