需求,给定相框大小,将所选图片等比缩放进相框居中位置
因为要求精确度不高,在计算时取了2位小数,对结果取整
/**
* 等比缩放图片并居中摆放
* @param width
* 图片宽
* @param height
* 图片高
* @param pWidth
* 父容器宽
* @param pHeight
* 父容器高
*/
computeImageStyle (width, height, pWidth, pHeight) {
let imageWidth = width
let imageHeight = height
let marginTop = null // 图片到相框上边距离
let marginLeft = null // 图片到相框左边距离
let widthRation = Number(pWidth/imageWidth + '').toFixed(2)*1 // 相框与图片宽的比
let heightRation = Number(pHeight/imageHeight + '').toFixed(2)*1 // 相框与图片高的比
if(widthRation <= heightRation){
// 按图片宽等比调整
if(widthRation >= 1) {
//使用原图片的宽高,并计算样式
marginTop = Number((pHeight - imageHeight)/2 + '').toFixed(2)*1
marginTop = (marginTop + '').split('.')[0]
marginLeft = Number((pWidth - imageWidth)/2 + '').toFixed(2)*1
marginLeft = (marginLeft + '').split('.')[0]
}else{
imageHeight = Number(imageHeight*widthRation + '').toFixed(2)*1
imageHeight = (imageHeight + '').split('.')[0] // 取整
imageWidth = (pWidth + '').split('.')[0]
marginTop = Number((pHeight - imageHeight)/2 + '').toFixed(2)*1
marginTop = (marginTop + '').split('.')[0]
}
}else{
// 按图片高等比调整
if(heightRation >= 1) {
//使用原图片的宽高,并计算样式
marginTop = Number((pHeight - imageHeight)/2 + '').toFixed(2)*1
marginTop = (marginTop + '').split('.')[0]
marginLeft = Number((pWidth - imageWidth)/2 + '').toFixed(2)*1
marginLeft = (marginLeft + '').split('.')[0]
}else{
imageWidth = Number(imageWidth*heightRation + '').toFixed(2)*1
imageWidth = (imageWidth + '').split('.')[0] // 取整
imageHeight = (pHeight + '').split('.')[0]
marginLeft = Number((pWidth - imageWidth)/2 + '').toFixed(2)*1
marginLeft = (marginLeft + '').split('.')[0]
}
}
return {width: imageWidth, height: imageHeight, marginTop: marginTop, marginLeft: marginLeft}
}
margin为null的不设置样式
1473

被折叠的 条评论
为什么被折叠?



