/*
* polycasso - Cubism Artwork generator
* Copyright 2009-2017 MeBigFatGuy.com
* Copyright 2009-2017 Dave Brosius
* Inspired by work by Roger Alsing
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations
* under the License.
*/
package com.mebigfatguy.polycasso;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Polygon;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* generates an svg file from the set of polygons
*/
public class SVGSaver implements Saver {
/**
* saves the set of polygons in an svg file
*
* @param fileName the name of the file to write to
* @param imageSize the dimension of the image
* @param data the polygons to draw
*/
@Override
public void save(String fileName, Dimension imageSize, PolygonData[] data)
throws IOException {
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))) {
pw.print("<svg xmlns=\"http://www.w3.org/2000/svg\"");
pw.print(" width=\"");
pw.print(imageSize.width);
pw.print("px\" height=\"");
pw.print(imageSize.height);
pw.println("px\" version=\"1.2\">");
pw.println("\t<!-- generated by Polycasso (http://polycasso.sourceforge.net) -->");
pw.print("\t<rect x=\"0\" y=\"0\" width=\"");
pw.print(imageSize.width);
pw.print("px\" height=\"");
pw.print(imageSize.height);
pw.println("px\" fill=\"black\"/>");
pw.println("\t<g comp-op=\"src-over\">");
for (PolygonData pd : data) {
Polygon polygon = pd.getPolygon();
Color color = pd.getColor();
float alpha = pd.getAlpha();
pw.print("\t\t<polygon fill=\"#");
pw.print(toHexColor(color));
pw.print("\" fill-opacity=\"");
pw.print(alpha);
pw.print("\" points=\"");
String space = "";
for (int p = 0; p < polygon.npoints; p++) {
pw.print(space);
pw.print(polygon.xpoints[p]);
pw.print(",");
pw.print(polygon.ypoints[p]);
space = " ";
}
pw.println("\"/>");
}
pw.println("\t</g>");
pw.println("</svg>");
}
}
/**
* converts a color to an html encoded color string ie #003322
*
* @param color the color to convert
* @return the hex (html) string version of the color
*/
private String toHexColor(Color color) {
String r = Integer.toHexString(color.getRed());
if (r.length() == 1)
r = "0" + r;
String g = Integer.toHexString(color.getGreen());
if (g.length() == 1)
g = "0" + g;
String b = Integer.toHexString(color.getBlue());
if (b.length() == 1)
b = "0" + b;
return r + g + b;
}
}