我在表格的单元格中添加了图像,但它不适合整个高度。
高度不固定,可以在2行之间变化。
我的图像如何适应细胞的整个高度?
这是我的问题:
这是我的表的创建代码:
int nbColumns = 7 + planning.size() *4;
Table table = new Table(nbColumns);
table.setWidthPercent(100);
table.addCell(createCell(""));
table.addCell(createCell("Col1"));
table.addCell(createCell("Col2"));
DateFormat hourFormat = new SimpleDateFormat("HH", Locale.FRENCH);
for(Date hourDate : planning){
table.addCell(new Cell(1,4).setTextAlignment(TextAlignment.CENTER).add(hourFormat.format(hourDate)).setFont(regular).setFontSize(10));
}
table.addCell(createCell("Long"));
table.addCell(createCell("A"));
table.addCell(createCell("B"));
table.addCell(createCell(""));
这是我为每个单元格添加图像的方式:
String IMG = // my img path
table.addCell(createImageCell(IMG));
public static Cell createImageCell(String path) throws MalformedURLException {
Image img = new Image(ImageDataFactory.create(path));
Cell cell = new Cell().add(img.setMargins(0,0,0,0).setAutoScaleHeight(true).setAutoScale(true)).setPadding(0);
cell.setBorder(null);
return cell;
}
最佳答案
为了获得可见性,将其发布为答案。
关于自动缩放:setAutoScaleHeight()
当前在developer分支上的iText7中存在错误(因此,该错误将出现在7.0.5和更低版本中)。当前,它设置AUTO_SCALE_WIDTH
(可能是由于复制粘贴的监督),除非已经设置了AUTO_SCALE_WIDTH
属性,否则它将把它们都设置为false并将AUTO_SCALE
设置为true。
修正错字不会导致预期的行为,因为我们现在已经知道了该问题,因此已将其工单添加到了待办事项中。
双向自动缩放(通过AUTO_SCALE
属性)可以正常工作,但是会均匀缩放,因此仅在单元格的高度大于宽度的情况下才缩放到宽度。
至于临时解决方案或绕过它的技巧,除了等待修复之外,我目前没有通用的:(
我用相对高度声明(应该包含在7.0.5中)进行了快速测试,但是又再次均匀缩放了图像。某些试验和错误以及Image.scaleAbsolute()
可以得到所需的结果,但这几乎无法自动化。从理论上讲,您可以编写自己的自定义CellRenderer,提取要排成行的最大Cell的高度以与scaleAbsolute()
结合使用,从而加入布局过程,但是您自己正在编写自动缩放逻辑点。
为了传播良好实践,还对OP的已发布代码进行了一些说明:
int nbColumns = 7 + planning.size() *4;
Table table = new Table(nbColumns);
不建议使用构造方法Table(int)(自7.0.2版开始),并且可能导致更高版本出现意外行为(在改进表布局机制时已完成此操作)。最好传递一个
UnitValue[]
,最好使用UnitValue.createPercentArray(float[])
或UnitValue.createPercentArray(float[])
创建img.setMargins(0,0,0,0).setAutoScaleHeight(true).setAutoScale(true))
setAutoScale
之后的setAutoScaleHeight
使后者多余。