Android 获取drawable中图片的高度宽度

本文介绍了一种使用Java在Android环境中加载图片资源的方法,并通过ImageData类存储图片的资源ID、高度和宽度。利用BitmapFactory.Options可以避免在加载大图片时消耗过多内存,同时提供了获取图片尺寸的代码实现。

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

1.定义一个ImageData类如下:

package com.example.vidarecyclerviewstagger;

public class ImageData {

    private int resourceId;
    private int height;
    private int width;

    public ImageData(int resourceId,int height,int width){
        this.resourceId = resourceId;
        this.height = height;
        this.width = width;
    }

    public int getResourceId() {
        return resourceId;
    }

    public void setResourceId(int resourceId) {
        this.resourceId = resourceId;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }
}

2.在drawable中放置一些图片:

private static int[] imgRes = new int[]{R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,
        R.drawable.img5,R.drawable.img6,R.drawable.img7,R.drawable.img8,
        R.drawable.img9,R.drawable.img10,R.drawable.img11,R.drawable.img12,
        R.drawable.img13,R.drawable.img14,R.drawable.img15,R.drawable.img16};

3.获取每个图片的高度宽度并保存数据到mData中:

private ArrayList<ImageData> mData = new ArrayList<>();

public void InitData(){
    for(int i = 0;i < imgRes.length;i++){
        BitmapFactory.Options options = new BitmapFactory.Options();
        BitmapFactory.decodeResource(getResources(),imgRes[i],options);

        //获取图片的宽高
        int height = options.outHeight;
        int width = options.outWidth;

        Log.i("YYYY","图片的宽度:"+width+"图片的高度:"+height);
        ImageData imgData = new ImageData(imgRes[i],height,width);
        mData.add(imgData);
    }
}

关键代码就这么几句:

BitmapFactory.Options options = new BitmapFactory.Options();
BitmapFactory.decodeResource(getResources(),imgRes[i],options);

//获取图片的宽高
int height = options.outHeight;
int width = options.outWidth;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值