首页 > 其他分享 >手把手教你如何实现大量图片的自适应图片页面的排列

手把手教你如何实现大量图片的自适应图片页面的排列

时间:2022-11-29 23:31:42浏览次数:39  
标签:const item 手把手 list 图片 return 页面 row

手把手教你如何实现大量图片的自适应图片页面的排列_二维数组

前言

最近在开发一个批量展示图片的页面,图片的自适应排列是一个无法避免的问题

在付出了许多头发的代价之后,终于完成了图片排列,并封装成组件,最终效果如下:

手把手教你如何实现大量图片的自适应图片页面的排列_二维数组_02

1、设计思路

为了使结构清晰,我将图片列表处理成了二维数组,第一维为行,第二维为列

render() {
const { className } = this.props;
// imgs 为处理后的图片数据,二维数组
const { imgs } = this.state;


return (
<div
ref={ref => (this.containerRef = ref)}
className={className ? `w-image-list ${className}` : 'w-image-list'}
>
{Array.isArray(imgs) &&
imgs.map((row, i) => {
return ( // 渲染行
<div key={`image-row-${i}`} className="w-image-row">
{Array.isArray(row) &&
row.map((item, index) => {
return ( // 渲染列
<div
key={`image-${i}-${index}`}
className="w-image-item"
style={{
height: `${item.height}px`,
width: `${item.width}px`,
}}
onClick={() => {
this.handleSelect(item);
}}
>
<img src={item.url} alt={item.title} />
</div>
);
})}
</div>
);
})}
</div>
);
}

每一行的总宽度不能超过容器本身的宽度,当前行如果剩余宽度足够,就可以追加新图片。

而这就需要算出图片等比缩放后的宽度 imgWidth,前提条件是知道图片的原始宽高和缩放后的高度 imgHeight,通过接口获取到图片列表的时候,至少是有图片链接 url 的,通过 url 我们就能获取到图片的宽高。

如果后端的同事更贴心一点,直接就返回了图片宽高,就相当优秀了。

获取到图片的原始宽高之后,可以先预设一个图片高度 imgHeight 作为基准值,然后算出等比缩放之后的图片宽度

const imgWidth = Math.floor(item.width * imgHeight / item.height);

然后将单个图片通过递归的形式放到每一行进行校验,如果当前行能放得下,就放在当前行,否则判断下一行,或者直接开启新的一行

2、数据结构

整体的方案设计好了之后,就可以确定最终处理好的图片数据应该是这样的:

const list = [
[
{id: String, width: Number, height: Number, title: String, url: String},
{id: String, width: Number, height: Number, title: String, url: String},
],[
{id: String, width: Number, height: Number, title: String, url: String},
{id: String, width: Number, height: Number, title: String, url: String},
]
]

不过为了方便计算每一行的总宽度,并在剩余宽度不足时提前完成当前行的排列,所以在计算的过程中,这样的数据结构更合适:

const rows = [
{
img: [], // 图片信息,最终只保留该字段
total: 0, // 总宽度
over: false, // 当前行是否完成排列
},
{
img: [],
total: 0,
over: false,
}
]

最后只需要将 rows 中的 img 提出来,生成二维数组 list 即可 。

基础数据结构明确了之后,接下来先写一个给新增行添加默认值的基础函数

// 以函数的形式处理图片列表默认值
const defaultRow = () => ({
img: [], // 图片信息,最终只保留该字段
total: 0, // 总宽度
over: false, // 当前行是否完成
});

为什么会采用函数的形式添加默认值呢?其实这和 vue 的 data 为什么会采用函数是一个道理。

如果直接定义一个纯粹的对象作为默认值,会让所有的行数据都共享引用同一个数据对象。

而通过 defaultRow 函数,每次创建一个新实例后,会返回一个全新副本数据对象,就不会有共同引用的问题。


3、向当前行追加图片

我设置了一个缓冲值,假如当前行的总宽度与容器宽度(每行的宽度上限)的差值在缓冲值之内,这一行就没法再继续添加图片,可以直接将当前行的状态标记为“已完成”。

const BUFFER = 30; // 单行宽度缓冲值

然后是将图片放到行里面的函数,分为两部分:递归判断是否将图片放到哪一行,将图片添加到对应行。

/**
* 向某一行追加图片
* @param {Array} list 列表
* @param {Object} img 图片数据
* @param {Number} row 当前行 index
* @param {Number} max 单行最大宽度
*/
function addImgToRow(list, img, row, max) {
if (!list[row]) {
// 新增一行
list[row] = defaultRow();
}
const total = list[row].total;
const innerList = jsON.parse(jsON.stringify(list));
innerList[row].img.push(img);
innerList[row].total = total + img.width;
// 当前行若空隙小于缓冲值,则不再补图
if (max - innerList[row].total < BUFFER) {
innerList[row].over = true;
}
return innerList;
}


/**
* 递归添加图片
* @param {Array} list 列表
* @param {Number} row 当前行 index
* @param {Objcet} opt 补充参数
*/
function pushImg(list, row, opt) {
const { maxWidth, item } = opt;
if (!list[row]) {
list[row] = defaultRow();
}
const total = list[row].total; // 当前行的总宽度
if (!list[row].over && item.width + total < maxWidth + BUFFER) {
// 宽度足够时,向当前行追加图片
return addImgToRow(list, item, row, maxWidth);
} else {
// 宽度不足,判断下一行
return pushImg(list, row + 1, opt);
}
}

4、处理图片数据

大部分的准备工作已经完成,可以试着处理图片数据了。

constructor(props) {
super(props);
this.containerRef = null;
this.imgHeight = this.props.imgHeight || 200;
this.state = {
imgs: null,
};
}
componentDidMount() {
const { list = mock } = this.props;
console.time('CalcWidth');
// 在构造函数 constructor 中定义 this.containerRef = null;
const imgs = this.calcWidth(list, this.containerRef.clientWidth, this.imgHeight);
console.timeEnd('CalcWidth');
this.setState({ imgs });
}

处理图片的主函数

/**
* 处理数据,根据图片宽度生成二维数组
* @param {Array} list 数据集
* @param {Number} maxWidth 单行最大宽度,通常为容器宽度
* @param {Number} imgHeight 每行的基准高度,根据这个高度算出图片宽度,最终为对齐图片,高度会有浮动
* @param {Boolean} deal 是否处理异常数据,默认处理
* @return {Array} 二维数组,按行保存图片宽度
*/
calcWidth(list, maxWidth, imgHeight, deal = true) {
if (!Array.isArray(list) || !maxWidth) {
return;
}
const innerList = jsON.parse(jsON.stringify(list));
const remaindArr = []; // 兼容不含宽高的数据
let allRow = [defaultRow()]; // 初始化第一行


for (const item of innerList) {


// 处理不含宽高的数据,统一延后处理
if (!item.height || !item.width) {
remaindArr.push(item);
continue;
}
const imgWidth = Math.floor(item.width * imgHeight / item.height);
item.width = imgWidth;
item.height = imgHeight;
// 单图成行
if (imgWidth >= maxWidth) {
allRow = addImgToRow(allRow, item, allRow.length, maxWidth);
continue;
}
// 递归处理当前图片
allRow = pushImg(allRow, 0, { maxWidth, item });
}
console.log('allRow======>', maxWidth, allRow);
// 处理异常数据
deal && this.initRemaindImg(remaindArr);
return buildImgList(allRow, maxWidth);
}

主函数 calcWidth 的最后两行,首先处理了没有原始宽高的异常数据(下一部分细讲),然后将带有行信息的图片数据处理为二维数组。

递归之后的图片数据按行保存,但每一行的总宽度都和实际容器的宽度有出入,如果直接使用当前的图片宽高,会导致每一行参差不齐。

所以需要使用 buildImgList 来整理图片,主要作用有两个,第一个作用是将图片数据处理为上面提到的二维数组函数。

第二个作用则是用容器的宽度来重新计算图片高宽,让图片能够对齐容器:

// 提取图片列表
function buildImgList(list, max) {
const res = [];
Array.isArray(list) &&
list.map(row => {
res.push(alignImgRow(row.img, (max / row.total).toFixed(2)));
});
return res;
}


// 调整单行高度以左右对齐
function alignImgRow(arr, coeff) {
if (!Array.isArray(arr)) {
return arr;
}
const coe = +coeff; // 宽高缩放系数
return arr.map(x => {
return {
...x,
width: x.width * coe,
height: x.height * coe,
};
});
}

5、处理没有原始宽高的图片

上面处理图片的主函数 calcWidth 在遍历数据的过程中,将没有原始宽高的数据单独记录了下来,放到最后处理。

对于这一部分数据,首先需要根据图片的 url 获取到图片的宽高。

// 根据 url 获取图片宽高
function checkImgWidth(url) {
return new Promise((resolve, reject) => {
const img = new Image();


img.onload = function() {
const res = {
width: this.width,
height: this.height,
};
resolve(res);
};
img.src = url;
});
}

需要注意的是,这个过程是异步的,所以我没有将这部分数据和上面的图片数据一起处理。

而是当所有图片宽高都查询到之后,再额外处理这部分数据,并将结果拼接到之前的图片后面。

// 处理没有宽高信息的图片数据
initRemaindImg(list) {
const arr = []; // 获取到宽高之后的数据
let count = 0;
list && list.map(x => {
checkImgWidth(x.url).then(res => {
count++;
arr.push({ ...x, ...res })
if (count === list.length) {
const { imgs } = this.state;
// 为防止数据异常导致死循环,本次 calcWidth 不再处理错误数据
const imgs2 = this.calcWidth(arr, this.containerRef.clientWidth - 10, this.imgHeight, false);
this.setState({ imgs: imgs.concat(imgs2) });
}
})
})
}

6、完整代码

import react from 'react';


const BUFFER = 30; // 单行宽度缓冲值


// 以函数的形式处理图片列表默认值
const defaultRow = () => ({
img: [], // 图片信息,最终只保留该字段
total: 0, // 总宽度
over: false, // 当前行是否完成
});


/**
* 向某一行追加图片
* @param {Array} list 列表
* @param {Object} img 图片数据
* @param {Number} row 当前行 index
* @param {Number} max 单行最大宽度
*/
function addImgToRow(list, img, row, max) {
if (!list[row]) {
// 新增一行
list[row] = defaultRow();
}
const total = list[row].total;
const innerList = jsON.parse(jsON.stringify(list));
innerList[row].img.push(img);
innerList[row].total = total + img.width;
// 当前行若空隙小于缓冲值,则不再补图
if (max - innerList[row].total < BUFFER) {
innerList[row].over = true;
}
return innerList;
}


/**
* 递归添加图片
* @param {Array} list 列表
* @param {Number} row 当前行 index
* @param {Objcet} opt 补充参数
*/
function pushImg(list, row, opt) {
const { maxWidth, item } = opt;
if (!list[row]) {
list[row] = defaultRow();
}
const total = list[row].total; // 当前行的总宽度
if (!list[row].over && item.width + total < maxWidth + BUFFER) {
// 宽度足够时,向当前行追加图片
return addImgToRow(list, item, row, maxWidth);
} else {
// 宽度不足,判断下一行
return pushImg(list, row + 1, opt);
}
}


// 提取图片列表
function buildImgList(list, max) {
const res = [];
Array.isArray(list) &&
list.map(row => {
res.push(alignImgRow(row.img, (max / row.total).toFixed(2)));
});
return res;
}


// 调整单行高度以左右对齐
function alignImgRow(arr, coeff) {
if (!Array.isArray(arr)) {
return arr;
}
const coe = +coeff; // 宽高缩放系数
return arr.map(x => {
return {
...x,
width: x.width * coe,
height: x.height * coe,
};
});
}


// 根据 url 获取图片宽高
function checkImgWidth(url) {
return new Promise((resolve, reject) => {
const img = new Image();


img.onload = function() {
const res = {
width: this.width,
height: this.height,
};
resolve(res);
};
img.src = url;
});
}


export default class ImageList extends react.Component {
constructor(props) {
super(props);
this.containerRef = null;
this.imgHeight = this.props.imgHeight || 200;
this.state = {
imgs: null,
};
}
componentDidMount() {
const { list } = this.props;
console.time('CalcWidth');
// 在构造函数 constructor 中定义 this.containerRef = null;
const imgs = this.calcWidth(list, this.containerRef.clientWidth, this.imgHeight);
console.timeEnd('CalcWidth');
this.setState({ imgs });
}


/**
* 处理数据,根据图片宽度生成二维数组
* @param {Array} list 数据集
* @param {Number} maxWidth 单行最大宽度,通常为容器宽度
* @param {Number} imgHeight 每行的基准高度,根据这个高度算出图片宽度,最终为对齐图片,高度会有浮动
* @param {Boolean} deal 是否处理异常数据,默认处理
* @return {Array} 二维数组,按行保存图片宽度
*/
calcWidth(list, maxWidth, imgHeight, deal = true) {
if (!Array.isArray(list) || !maxWidth) {
return;
}
const innerList = jsON.parse(jsON.stringify(list));
const remaindArr = []; // 兼容不含宽高的数据
let allRow = [defaultRow()]; // 初始化第一行


for (const item of innerList) {


// 处理不含宽高的数据,统一延后处理
if (!item.height || !item.width) {
remaindArr.push(item);
continue;
}
const imgWidth = Math.floor(item.width * imgHeight / item.height);
item.width = imgWidth;
item.height = imgHeight;
// 单图成行
if (imgWidth >= maxWidth) {
allRow = addImgToRow(allRow, item, allRow.length, maxWidth);
continue;
}
// 递归处理当前图片
allRow = pushImg(allRow, 0, { maxWidth, item });
}
console.log('allRow======>', maxWidth, allRow);
// 处理异常数据
deal && this.initRemaindImg(remaindArr);
return buildImgList(allRow, maxWidth);
}


// 处理没有宽高信息的图片数据
initRemaindImg(list) {
const arr = []; // 获取到宽高之后的数据
let count = 0;
list && list.map(x => {
checkImgWidth(x.url).then(res => {
count++;
arr.push({ ...x, ...res })
if (count === list.length) {
const { imgs } = this.state;
// 为防止数据异常导致死循环,本次 calcWidth 不再处理错误数据
const imgs2 = this.calcWidth(arr, this.containerRef.clientWidth - 10, this.imgHeight, false);
this.setState({ imgs: imgs.concat(imgs2) });
}
})
})
}


handleSelect = item => {
console.log('handleSelect', item);
};


render() {
const { className } = this.props;
// imgs 为处理后的图片数据,二维数组
const { imgs } = this.state;


return (
<div
ref={ref => (this.containerRef = ref)}
className={className ? `w-image-list ${className}` : 'w-image-list'}
>
{Array.isArray(imgs) &&
imgs.map((row, i) => {
return ( // 渲染行
<div key={`image-row-${i}`} className="w-image-row">
{Array.isArray(row) &&
row.map((item, index) => {
return ( // 渲染列
<div
key={`image-${i}-${index}`}
className="w-image-item"
style={{
height: `${item.height}px`,
width: `${item.width}px`,
}}
onClick={() => {
this.handleSelect(item);
}}
>
<img src={item.url} alt={item.title} />
</div>
);
})}
</div>
);
})}
</div>
);
}
}

PS: 记得给每个图片 item 添加样式 box-sizing: border-box。

手把手教你如何实现大量图片的自适应图片页面的排列_宽高_03

手把手教你如何实现大量图片的自适应图片页面的排列_宽高_04


标签:const,item,手把手,list,图片,return,页面,row
From: https://blog.51cto.com/u_15809510/5897278

相关文章