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;