使用ChartDirector的XYChart绘制Simple Table

By | 2015年9月24日

只能绘制Simple Table,是指Table的Cell不能被划分,一个Cell不能占据多行,也不能占据多列。

使用ChartDirector绘制Table的优势是,可以导出成各种格式的图片。尤其是可以导出成SVG图片,可以无限zoom in and zoom out。

绘制思路

ChartDirector的例子中有一个”Percentage Bar Chart”,如下图:

image

看起来已经有点像一个Table了,如果每层一样高,柱子之间没有间隔,这就是一个简单的Table。还有要去掉X轴、Y轴和Legend(右边的图标)。

Code Example


    // The values indicate each cell's height.
    double[] data0 = { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 };
    double[] data1 = { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50};
    double[] data2= { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 };
    double[] data3= { 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 };
    XYChart c = new XYChart(800, 340);
    c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, 0xe8f0f8, 0xaaccff), 0x88aaee);
    c.setRoundedFrame();
    c.setDropShadow();

    // Add a title to the chart using 15 points Arial Italic. Set top/bottom
    // margins to 15 pixels.
    TextBox title = c.addTitle("This is a simple table", "Arial Italic", 15);
    title.setMargin2(0, 0, 15, 15);

    c.setPlotArea(50, 60, 700, 200, 0xe8f0f8, -1, Chart.Transparent, 0xaaaaaa);

    // Don't show Axis
    c.xAxis().setColors(Chart.Transparent);
    c.yAxis().setColors(Chart.Transparent);
    c.yAxis().setOffset(-100, 0);

    // Add a percentage bar layer
    BarLayer layer = c.addBarLayer2(Chart.Percentage);
    layer.setBarGap(Chart.TouchBar, Chart.TouchBar);

    // The extra fields are the real table cell data.
    layer.addExtraField(new double[]{11, 34, 12, 33, 56, 11, 34, 12, 33, 56});
    layer.addExtraField(new double[]{44, 24, 90, 34, 46, 44, 24, 90, 34, 46});
    layer.addExtraField(new double[]{89, 32, 67, 23, 55, 89, 32, 67, 23, 55});
    layer.addExtraField(new String[]{"Head1", "Head2", "Head3", "Head4", "Head5", "Head6", "Head7", "Head8", "Head9", "Head10"});

    // Add table data to each bar layer. 
    // First parameter indicates binding to which layer. 
    // Second parameter indicates cell color.
    DataSet ds0 = layer.addDataSet(data0, 0xEBF1DE);
    ds0.setDataLabelStyle().setAlignment(Chart.Center);
    ds0.setDataLabelFormat("{field0}");
    DataSet ds1 = layer.addDataSet(data1, 0xEBF1DE, "<*block,valign=absmiddle*><*img=software.png*> Software<*/*>");
    ds1.setDataLabelStyle().setAlignment(Chart.Center);
    ds1.setDataLabelFormat("{field1}");
    DataSet ds2 = layer.addDataSet(data2, 0xEBF1DE, "<*block,valign=absmiddle*><*img=computer.png*> Hardware<*/*>");
    ds2.setDataLabelStyle().setAlignment(Chart.Center);
    ds2.setDataLabelFormat("{field2}");
    DataSet ds3 = layer.addDataSet(data3, 0x77933C);
    ds3.setDataLabelStyle().setAlignment(Chart.Center);
    ds3.setDataLabelFormat("{field3}");

    // Use soft lighting effect with light direction from top
    layer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Top));

    // Output the chart
    viewer.setChart(c);

Table效果

image