Repository: StanKocken/SVG2Drawable
Branch: master
Commit: caabd5df0036
Files: 22
Total size: 76.2 KB
Directory structure:
gitextract_job2c14h/
├── .classpath
├── .gitignore
├── .project
├── .settings/
│ └── org.eclipse.jdt.core.prefs
├── LICENSE
├── README.md
├── build.xml
├── src/
│ └── com/
│ └── skocken/
│ └── svgconverter/
│ ├── Unparse.java
│ └── svg/
│ ├── Element.java
│ ├── Gradient.java
│ ├── InstructionRecorder.java
│ ├── LinearGradient.java
│ ├── NumberParse.java
│ ├── ParserHelper.java
│ ├── Properties.java
│ ├── RadialGradient.java
│ ├── SVGHandler.java
│ ├── SVGParser.java
│ ├── SVGParsingMethods.java
│ ├── Shader.java
│ └── StyleSet.java
└── svg_converter.jar
================================================
FILE CONTENTS
================================================
================================================
FILE: .classpath
================================================
================================================
FILE: .gitignore
================================================
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/bin
================================================
FILE: .project
================================================
SVGtoDrawable
org.eclipse.jdt.core.javabuilder
org.eclipse.jdt.core.javanature
================================================
FILE: .settings/org.eclipse.jdt.core.prefs
================================================
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
================================================
FILE: README.md
================================================
SVG2Drawable
============
Use a jar executable to create a Drawable class to display a SVG on Android.
This is a standalone library, not a Runtime Android library. You need to use it BEFORE your Android compilation (and only once per SVG file).
## Why?
I want to use a scalable image format.
A SVG sounds really good but it's a bit long to load (mainly the time to parse the XML) and I didn't find any library that support the Hardware acceleration.
## How does it work?
My main goal is to have a [Drawable](http://developer.android.com/reference/android/graphics/drawable/Drawable.html) class:
* Made a fork of the [svg-android](https://code.google.com/p/svg-android/) library.
* Replaced any instructions to create a [Picture](http://developer.android.com/reference/android/graphics/Picture.html) to collect them into a Logger.
* Print this Logger.
* Save it to a Drawable java class.
## How to use it?
You can read the code but I'm not proud of it. I started to do a POC for a basic usage and now I need to transform the code to make it more readable and robust.
You can simply use the [jar provided into this repo](https://github.com/StanKocken/SVG2Drawable/blob/master/svg_converter.jar) by specify:
* the SVG file
* the package where you want to put the Drawable
* the drawable name
You can also specify the output of the script to create a file. By adding "> filename.java".
java -jar svg_converter.jar example.svg com.skocken.svg.example.drawable ExampleDrawable > ExampleDrawable.java
Now, copy this "ExampleDrawable.java" into your Android project, into the package "com.skocken.svg.example.drawable" (from this example), and add it to your ImageView into your code with:
imageview.setImageDrawable(new ExampleDrawable());

## License
* [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
## Contributing
If you found a SVG with a problem, you can open an issue. Please, if possible, let me know if this same SVG work with the library [svg-android](https://code.google.com/p/svg-android/).
Please fork this repository and contribute back using
[pull requests](https://github.com/StanKocken/SVG2Drawable/pulls).
Any contributions, large or small, major features, bug fixes, additional
language translations, unit/integration tests are welcomed and appreciated
but will be thoroughly reviewed and discussed.
================================================
FILE: build.xml
================================================
================================================
FILE: src/com/skocken/svgconverter/Unparse.java
================================================
package com.skocken.svgconverter;
import java.io.FileInputStream;
import com.skocken.svgconverter.svg.SVGParser;
public class Unparse {
public static void main(String[] args) {
if (args.length == 3) {
try {
SVGParser.getSVGFromInputStream(args[1], args[2], new FileInputStream(args[0]));
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Some paramaters are missing. Should be 'path', 'package name' and 'class name'.");
}
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/Element.java
================================================
package com.skocken.svgconverter.svg;
public class Element {
private String name;
private boolean canvasSave;
public Element(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean hasCanvasSave() {
return canvasSave;
}
public void setHasCanvasSave() {
this.canvasSave = true;
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/Gradient.java
================================================
package com.skocken.svgconverter.svg;
// import android.graphics.Matrix;
import java.util.ArrayList;
public class Gradient {
String id;
String xlink;
boolean isLinear;
float x1, y1, x2, y2;
float x, y, radius;
ArrayList positions = new ArrayList();
ArrayList colors = new ArrayList();
InstructionRecorder matrixInstructions = new InstructionRecorder();
public Gradient createChild(Gradient g) {
Gradient child = new Gradient();
child.id = g.id;
child.xlink = id;
child.isLinear = g.isLinear;
child.x1 = g.x1;
child.x2 = g.x2;
child.y1 = g.y1;
child.y2 = g.y2;
child.x = g.x;
child.y = g.y;
child.radius = g.radius;
child.positions = positions;
child.colors = colors;
child.matrixInstructions = matrixInstructions;
if (g.matrixInstructions != null) {
if (matrixInstructions == null) {
child.matrixInstructions = g.matrixInstructions;
} else {
// Matrix m = new Matrix(matrixInstructions);
// m.preConcat(g.matrixInstructions);
// child.matrixInstructions = m;
child.matrixInstructions = g.matrixInstructions;
}
}
return child;
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/InstructionRecorder.java
================================================
package com.skocken.svgconverter.svg;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class InstructionRecorder {
private static final int MAX_LENGTH_LOG = 3800;
private List listInstructions = new ArrayList();
public void addBegin(String instructions, Object... args) {
listInstructions.add(0, format(instructions, args));
}
public void add(String instructions, Object... args) {
listInstructions.add(format(instructions, args));
}
public List getListInstructions() {
return listInstructions;
}
public boolean isEmpty() {
return listInstructions.isEmpty();
}
public void print() {
StringBuffer sb = new StringBuffer();
for (String instruction : listInstructions) {
if (sb.length() + instruction.length() > MAX_LENGTH_LOG) {
System.out.println(sb.toString());
sb.setLength(0);
}
sb.append(instruction);
sb.append("\r\n");
}
System.out.println(sb.toString());
}
private String format(String instructions, Object[] args) {
return String.format(Locale.ENGLISH, instructions, args);
}
public void add(InstructionRecorder instructions) {
if (instructions == null || instructions.isEmpty()) {
return;
}
listInstructions.addAll(instructions.listInstructions);
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/LinearGradient.java
================================================
package com.skocken.svgconverter.svg;
public class LinearGradient extends Shader {
private float mX0;
private float mY0;
private float mX1;
private float mY1;
private int[] mColors;
private float[] mPositions;
private String mTileMode;
public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, String tileMode) {
super();
mX0 = x0;
mY0 = y0;
mX1 = x1;
mY1 = y1;
mColors = colors;
mPositions = positions;
mTileMode = tileMode;
}
@Override
public void printTo(InstructionRecorder drawInstructions) {
drawInstructions.add("{");
StringBuffer sb = new StringBuffer("int[] colors = ");
if (mColors == null) {
sb.append("null;");
} else {
sb.append(" { ");
int startIterationLength = sb.length();
for (int color : mColors) {
if (sb.length() > startIterationLength) {
sb.append(", ");
}
sb.append(color);
}
sb.append(" }; ");
}
drawInstructions.add(sb.toString());
sb = new StringBuffer("float[] positions = ");
if (mPositions == null) {
sb.append("null;");
} else {
sb.append(" { ");
int startIterationLength = sb.length();
for (float position : mPositions) {
if (sb.length() > startIterationLength) {
sb.append(", ");
}
sb.append(position);
sb.append("f");
}
sb.append(" }; ");
}
drawInstructions.add(sb.toString());
drawInstructions.add("shader = new LinearGradient(%ff, %ff, %ff, %ff, colors, positions, %s);", mX0, mY0, mX1, mY1, mTileMode);
drawInstructions.add("}");
printMatrixTo(drawInstructions);
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/NumberParse.java
================================================
package com.skocken.svgconverter.svg;
import java.util.ArrayList;
public class NumberParse {
private ArrayList numbers;
private int nextCmd;
public NumberParse(ArrayList numbers, int nextCmd) {
this.numbers = numbers;
this.nextCmd = nextCmd;
}
public int getNextCmd() {
return nextCmd;
}
public int size() {
return numbers.size();
}
public float getNumber(int index) {
return numbers.get(index);
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/ParserHelper.java
================================================
package com.skocken.svgconverter.svg;
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
*/
/**
* Parses numbers from SVG text. Based on the Batik Number Parser (Apache 2 License).
*
* @author Apache Software Foundation, Larva Labs LLC
*/
public class ParserHelper {
private char current;
private CharSequence s;
public int pos;
private int n;
public ParserHelper(CharSequence s, int pos) {
this.s = s;
this.pos = pos;
n = s.length();
current = s.charAt(pos);
}
private char read() {
if (pos < n) {
pos++;
}
if (pos == n) {
return '\0';
} else {
return s.charAt(pos);
}
}
public void skipWhitespace() {
while (pos < n) {
if (Character.isWhitespace(s.charAt(pos))) {
advance();
} else {
break;
}
}
}
public void skipNumberSeparator() {
while (pos < n) {
char c = s.charAt(pos);
switch (c) {
case ' ':
case ',':
case '\n':
case '\t':
advance();
break;
default:
return;
}
}
}
public void advance() {
current = read();
}
/**
* Parses the content of the buffer and converts it to a float.
*/
public float parseFloat() {
int mant = 0;
int mantDig = 0;
boolean mantPos = true;
boolean mantRead = false;
int exp = 0;
int expDig = 0;
int expAdj = 0;
boolean expPos = true;
switch (current) {
case '-':
mantPos = false;
// fallthrough
case '+':
current = read();
}
m1: switch (current) {
default:
return Float.NaN;
case '.':
break;
case '0':
mantRead = true;
l: for (;;) {
current = read();
switch (current) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
case '.': case 'e': case 'E':
break m1;
default:
return 0.0f;
case '0':
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
mantRead = true;
l: for (;;) {
if (mantDig < 9) {
mantDig++;
mant = mant * 10 + (current - '0');
} else {
expAdj++;
}
current = read();
switch (current) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
if (current == '.') {
current = read();
m2: switch (current) {
default:
case 'e': case 'E':
if (!mantRead) {
reportUnexpectedCharacterError( current );
return 0.0f;
}
break;
case '0':
if (mantDig == 0) {
l: for (;;) {
current = read();
expAdj--;
switch (current) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
default:
if (!mantRead) {
return 0.0f;
}
break m2;
case '0':
}
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
l: for (;;) {
if (mantDig < 9) {
mantDig++;
mant = mant * 10 + (current - '0');
expAdj--;
}
current = read();
switch (current) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
}
switch (current) {
case 'e': case 'E':
current = read();
switch (current) {
default:
reportUnexpectedCharacterError( current );
return 0f;
case '-':
expPos = false;
case '+':
current = read();
switch (current) {
default:
reportUnexpectedCharacterError( current );
return 0f;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
en: switch (current) {
case '0':
l: for (;;) {
current = read();
switch (current) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
default:
break en;
case '0':
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
l: for (;;) {
if (expDig < 3) {
expDig++;
exp = exp * 10 + (current - '0');
}
current = read();
switch (current) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
default:
}
if (!expPos) {
exp = -exp;
}
exp += expAdj;
if (!mantPos) {
mant = -mant;
}
return buildFloat(mant, exp);
}
private void reportUnexpectedCharacterError(char c) {
throw new RuntimeException("Unexpected char '" + c + "'.");
}
/**
* Computes a float from mantissa and exponent.
*/
public static float buildFloat(int mant, int exp) {
if (exp < -125 || mant == 0) {
return 0.0f;
}
if (exp >= 128) {
return (mant > 0)
? Float.POSITIVE_INFINITY
: Float.NEGATIVE_INFINITY;
}
if (exp == 0) {
return mant;
}
if (mant >= (1 << 26)) {
mant++; // round up trailing bits if they will be dropped.
}
return (float) ((exp > 0) ? mant * pow10[exp] : mant / pow10[-exp]);
}
/**
* Array of powers of ten. Using double instead of float gives a tiny bit more precision.
*/
private static final double[] pow10 = new double[128];
static {
for (int i = 0; i < pow10.length; i++) {
pow10[i] = Math.pow(10, i);
}
}
public float nextFloat() {
skipWhitespace();
float f = parseFloat();
skipNumberSeparator();
return f;
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/Properties.java
================================================
package com.skocken.svgconverter.svg;
import static com.skocken.svgconverter.svg.SVGParsingMethods.getStringAttr;
import org.xml.sax.Attributes;
public class Properties {
StyleSet styles = null;
Attributes atts;
Properties(Attributes atts) {
this.atts = atts;
String styleAttr = getStringAttr("style", atts);
if (styleAttr != null) {
styles = new StyleSet(styleAttr);
}
}
public String getAttr(String name) {
String v = null;
if (styles != null) {
v = styles.getStyle(name);
}
if (v == null) {
v = getStringAttr(name, atts);
}
return v;
}
public String getString(String name) {
return getAttr(name);
}
public Integer getHex(String name) {
String v = getAttr(name);
if (v == null || !v.startsWith("#")) {
return null;
} else {
try {
return Integer.parseInt(v.substring(1), 16);
} catch (NumberFormatException nfe) {
// todo - parse word-based color here
return null;
}
}
}
public Float getFloat(String name, float defaultValue) {
Float v = getFloat(name);
if (v == null) {
return defaultValue;
} else {
return v;
}
}
public Float getFloat(String name) {
String v = getAttr(name);
if (v == null) {
return null;
} else {
try {
return Float.parseFloat(v);
} catch (NumberFormatException nfe) {
return null;
}
}
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/RadialGradient.java
================================================
package com.skocken.svgconverter.svg;
public class RadialGradient extends Shader {
private float mX;
private float mY;
private float mRadius;
private int[] mColors;
private float[] mPositions;
private String mTileMode;
public RadialGradient(float x, float y, float radius, int[] colors, float[] positions, String tileMode) {
super();
mX = x;
mY = y;
mRadius = radius;
mColors = colors;
mPositions = positions;
mTileMode = tileMode;
}
@Override
public void printTo(InstructionRecorder drawInstructions) {
drawInstructions.add("{");
StringBuffer sb = new StringBuffer("int[] colors = ");
if (mColors == null) {
sb.append("null;");
} else {
sb.append(" { ");
int startIterationLength = sb.length();
for (int color : mColors) {
if (sb.length() > startIterationLength) {
sb.append(", ");
}
sb.append(color);
}
sb.append(" }; ");
}
drawInstructions.add(sb.toString());
sb = new StringBuffer("float[] positions = ");
if (mPositions == null) {
sb.append("null;");
} else {
sb.append(" { ");
int startIterationLength = sb.length();
for (float position : mPositions) {
if (sb.length() > startIterationLength) {
sb.append(", ");
}
sb.append(position);
sb.append("f");
}
sb.append(" }; ");
}
drawInstructions.add(sb.toString());
drawInstructions.add("shader = new RadialGradient(%ff, %ff, %ff, colors, positions, %s);", mX, mY, mRadius, mTileMode);
drawInstructions.add("}");
printMatrixTo(drawInstructions);
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/SVGHandler.java
================================================
package com.skocken.svgconverter.svg;
import static com.skocken.svgconverter.svg.SVGParsingMethods.doPath;
import static com.skocken.svgconverter.svg.SVGParsingMethods.getFloatAttr;
import static com.skocken.svgconverter.svg.SVGParsingMethods.getNumberParseAttr;
import static com.skocken.svgconverter.svg.SVGParsingMethods.getStringAttr;
import static com.skocken.svgconverter.svg.SVGParsingMethods.parseTransform;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SVGHandler extends DefaultHandler {
List elements = new ArrayList();
HashMap gradientMap = new HashMap();
HashMap gradientRefMap = new HashMap();
Gradient gradient = null;
int height, width;
float viewBox[];
InstructionRecorder drawInstructions = new InstructionRecorder();
String packageName, className;
SVGHandler(String packageName, String className) {
this.packageName = packageName;
this.className = className;
drawInstructions.add("private RectF rect = new RectF();");
drawInstructions.add("private Matrix matrix = new Matrix();");
drawInstructions.add("private Shader shader;");
drawInstructions.add("private Path p = new Path();");
drawInstructions.add("private Paint paint = new Paint();");
drawInstructions.add("@Override");
drawInstructions.add("public void draw(Canvas canvas) {");
drawInstructions.add("paint.setAntiAlias(true);");
drawInstructions.add("float viewBoxWidth = VIEW_BOX[2];");
drawInstructions.add("float viewBoxHeight = VIEW_BOX[3];");
drawInstructions.add("Rect bounds = getBounds();");
drawInstructions.add("if (viewBoxHeight <= 0 || viewBoxWidth <= 0 || bounds.width() <= 0 || bounds.height() <= 0) {");
drawInstructions.add("return;");
drawInstructions.add("}");
drawInstructions.add("canvas.save();");
drawInstructions.add("float viewBoxRatio = viewBoxWidth / viewBoxHeight;");
drawInstructions.add("float boundsRatio = bounds.width() / (float) bounds.height();");
drawInstructions.add("float factorScale;");
drawInstructions.add("if (boundsRatio > viewBoxRatio) {");
drawInstructions.add(" // canvas larger than viewbox");
drawInstructions.add(" factorScale = bounds.height() / viewBoxHeight;");
drawInstructions.add("} else {");
drawInstructions.add(" // canvas higher (or equals) than viewbox");
drawInstructions.add(" factorScale = bounds.width() / viewBoxWidth;");
drawInstructions.add("}");
drawInstructions.add("int newViewBoxHeight = Math.round(factorScale * viewBoxHeight);");
drawInstructions.add("int newViewBoxWidth = Math.round(factorScale * viewBoxWidth);");
drawInstructions.add("int marginX = bounds.width() - newViewBoxWidth;");
drawInstructions.add("int marginY = bounds.height() - newViewBoxHeight;");
drawInstructions.add("canvas.translate(bounds.left, bounds.top);");
drawInstructions.add("canvas.translate(Math.round(marginX / 2f), Math.round(marginY / 2f));");
drawInstructions.add("canvas.clipRect(0, 0, newViewBoxWidth, newViewBoxHeight);");
drawInstructions.add("canvas.translate(-Math.round(factorScale * VIEW_BOX[0]), -Math.round(factorScale * VIEW_BOX[1]));");
}
public List getDrawInstructions() {
return drawInstructions.getListInstructions();
}
@Override
public void startDocument() throws SAXException {
// Set up prior to parsing a doc
}
@Override
public void endDocument() throws SAXException {
// Clean up after parsing a doc
if (viewBox == null) {
viewBox = new float[4];
viewBox[0] = 0;
viewBox[1] = 0;
viewBox[2] = width;
viewBox[3] = height;
}
float width = viewBox[2];
float height = viewBox[3];
float factorMin = Math.min(width / 10, height / 10);
int minWidth = Math.round(width / factorMin);
int minHeight = Math.round(height / (width / minWidth));
drawInstructions.addBegin("private static final float[] VIEW_BOX = { %ff, %ff, %ff, %ff };", viewBox[0], viewBox[1], viewBox[2], viewBox[3]);
drawInstructions.add("canvas.restore();");
drawInstructions.add("}");
drawInstructions.add("@Override public void setAlpha(int alpha) { }");
drawInstructions.add("@Override public void setColorFilter(ColorFilter cf) { }");
drawInstructions.add("@Override public int getOpacity() { return 0; }");
drawInstructions.add("@Override public int getMinimumHeight() { return %d; }", minHeight);
drawInstructions.add("@Override public int getMinimumWidth() { return %d; }", minWidth);
drawInstructions.add("}");
drawInstructions.addBegin("public class %s extends Drawable {", className);
drawInstructions.addBegin("import android.graphics.Canvas;");
drawInstructions.addBegin("import android.graphics.ColorFilter;");
drawInstructions.addBegin("import android.graphics.Matrix;");
drawInstructions.addBegin("import android.graphics.Paint;");
drawInstructions.addBegin("import android.graphics.Path;");
drawInstructions.addBegin("import android.graphics.Rect;");
drawInstructions.addBegin("import android.graphics.RectF;");
drawInstructions.addBegin("import android.graphics.LinearGradient;");
drawInstructions.addBegin("import android.graphics.RadialGradient;");
drawInstructions.addBegin("import android.graphics.Shader;");
drawInstructions.addBegin("import android.graphics.drawable.Drawable;");
drawInstructions.addBegin("package %s;", packageName);
}
private boolean doFill(Properties atts, HashMap gradients) {
if ("none".equals(atts.getString("display"))) {
return false;
}
String fillString = atts.getString("fill");
if (fillString != null && fillString.startsWith("url(#")) {
// It's a gradient fill, look it up in our map
String id = fillString.substring("url(#".length(), fillString.length() - 1);
Shader shader = gradients.get(id);
if (shader != null) {
// Util.debug("Found shader!");
shader.printTo(drawInstructions);
drawInstructions.add("paint.setShader(shader);");
drawInstructions.add("paint.setStyle(Paint.Style.FILL);");
return true;
} else {
// Util.debug("Didn't find shader!");
return false;
}
} else {
drawInstructions.add("paint.setShader(null);");
Integer color = atts.getHex("fill");
if (color != null) {
doColor(atts, color, true);
drawInstructions.add("paint.setStyle(Paint.Style.FILL);");
return true;
} else if (atts.getString("fill") == null && atts.getString("stroke") == null) {
// Default is black fill
drawInstructions.add("paint.setStyle(Paint.Style.FILL);");
drawInstructions.add("paint.setColor(0xFF000000);");
return true;
}
}
return false;
}
private boolean doStroke(Properties atts) {
if ("none".equals(atts.getString("display"))) {
return false;
}
Integer color = atts.getHex("stroke");
if (color != null) {
doColor(atts, color, false);
// Check for other stroke attributes
Float width = atts.getFloat("stroke-width");
// Set defaults
if (width != null) {
drawInstructions.add("paint.setStrokeWidth(%ff);", width);
}
String linecap = atts.getString("stroke-linecap");
if ("round".equals(linecap)) {
drawInstructions.add("paint.setStrokeCap(Paint.Cap.ROUND);");
} else if ("square".equals(linecap)) {
drawInstructions.add("paint.setStrokeCap(Paint.Cap.SQUARE);");
} else if ("butt".equals(linecap)) {
drawInstructions.add("paint.setStrokeCap(Paint.Cap.BUTT);");
}
String linejoin = atts.getString("stroke-linejoin");
if ("miter".equals(linejoin)) {
drawInstructions.add("paint.setStrokeCap(Paint.Cap.MITER);");
} else if ("round".equals(linejoin)) {
drawInstructions.add("paint.setStrokeCap(Paint.Cap.ROUND);");
} else if ("bevel".equals(linejoin)) {
drawInstructions.add("paint.setStrokeCap(Paint.Cap.BEVEL);");
}
drawInstructions.add("paint.setStyle(Paint.Style.STROKE);");
return true;
}
return false;
}
private Gradient doGradient(boolean isLinear, Attributes atts) {
Gradient gradient = new Gradient();
gradient.id = getStringAttr("id", atts);
gradient.isLinear = isLinear;
if (isLinear) {
gradient.x1 = getFloatAttr("x1", atts, 0f);
gradient.x2 = getFloatAttr("x2", atts, 0f);
gradient.y1 = getFloatAttr("y1", atts, 0f);
gradient.y2 = getFloatAttr("y2", atts, 0f);
} else {
gradient.x = getFloatAttr("cx", atts, 0f);
gradient.y = getFloatAttr("cy", atts, 0f);
gradient.radius = getFloatAttr("r", atts, 0f);
}
String transform = getStringAttr("gradientTransform", atts);
if (transform != null) {
gradient.matrixInstructions = parseTransform(new InstructionRecorder(), transform);
}
String xlink = getStringAttr("href", atts);
if (xlink != null) {
if (xlink.startsWith("#")) {
xlink = xlink.substring(1);
}
gradient.xlink = xlink;
}
return gradient;
}
private void doColor(Properties atts, Integer color, boolean fillMode) {
int c = (0xFFFFFF & color) | 0xFF000000;
drawInstructions.add("paint.setColor(%d);", c);
Float opacity = atts.getFloat("opacity");
if (opacity == null) {
opacity = atts.getFloat(fillMode ? "fill-opacity" : "stroke-opacity");
}
if (opacity == null) {
drawInstructions.add("paint.setAlpha(255);");
} else {
drawInstructions.add("paint.setAlpha(%d);", (int) (255 * opacity));
}
}
private boolean hidden = false;
private int hiddenLevel = 0;
private boolean boundsMode = false;
private boolean defsMode = false;
private boolean pushTransform(Attributes atts) {
final String transform = getStringAttr("transform", atts);
if (transform != null) {
parseTransform(drawInstructions, transform);
drawInstructions.add("canvas.save();");
drawInstructions.add("canvas.concat(matrix);");
return true;
} else {
return false;
}
}
private void popTransform() {
drawInstructions.add("canvas.restore();");
}
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
// Reset paint opacity
drawInstructions.add("paint.setAlpha(255);");
if (localName == null || localName.length() == 0) {
localName = qName;
}
Element element = new Element(localName);
elements.add(0, element);
// Ignore everything but rectangles in bounds mode
if (boundsMode) {
return;
}
// Ignore defs
if (defsMode) {
return;
}
if (localName.equals("svg")) {
width = (int) Math.ceil(getFloatAttr("width", atts, 0f));
height = (int) Math.ceil(getFloatAttr("height", atts, 0f));
String viewBoxStr = getStringAttr("viewBox", atts);
if (viewBoxStr != null) {
String[] split = viewBoxStr.split(" ");
if (split.length == 4) {
viewBox = new float[4];
viewBox[0] = Float.parseFloat(split[0]);
viewBox[1] = Float.parseFloat(split[1]);
viewBox[2] = Float.parseFloat(split[2]);
viewBox[3] = Float.parseFloat(split[3]);
}
}
} else if (localName.equals("defs")) {
// Ignore
defsMode = true;
} else if (localName.equals("linearGradient")) {
gradient = doGradient(true, atts);
} else if (localName.equals("radialGradient")) {
gradient = doGradient(false, atts);
} else if (localName.equals("stop")) {
if (gradient != null) {
float offset = getFloatAttr("offset", atts);
String styles = getStringAttr("style", atts);
StyleSet styleSet = new StyleSet(styles);
String colorStyle = styleSet.getStyle("stop-color");
int color = 0xFF000000;
if (colorStyle != null) {
if (colorStyle.startsWith("#")) {
color = Integer.parseInt(colorStyle.substring(1), 16);
} else {
color = Integer.parseInt(colorStyle, 16);
}
}
String opacityStyle = styleSet.getStyle("stop-opacity");
if (opacityStyle != null) {
float alpha = Float.parseFloat(opacityStyle);
int alphaInt = Math.round(255 * alpha);
color |= (alphaInt << 24);
} else {
color |= 0xFF000000;
}
gradient.positions.add(offset);
gradient.colors.add(color);
}
} else if (localName.equals("g")) {
// Check to see if this is the "bounds" layer
if ("bounds".equalsIgnoreCase(getStringAttr("id", atts))) {
boundsMode = true;
}
if (hidden) {
hiddenLevel++;
// Util.debug("Hidden up: " + hiddenLevel);
}
// Go in to hidden mode if display is "none"
if ("none".equals(getStringAttr("display", atts))) {
if (!hidden) {
hidden = true;
hiddenLevel = 1;
// Util.debug("Hidden up: " + hiddenLevel);
}
}
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
} else if (!hidden && localName.equals("rect")) {
Float x = getFloatAttr("x", atts);
if (x == null) {
x = 0f;
}
Float y = getFloatAttr("y", atts);
if (y == null) {
y = 0f;
}
Float width = getFloatAttr("width", atts);
Float height = getFloatAttr("height", atts);
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
Properties props = new Properties(atts);
if (doFill(props, gradientMap)) {
drawInstructions.add("canvas.drawRect(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, paint);", x, y, x + width, y + height);
}
if (doStroke(props)) {
drawInstructions.add("canvas.drawRect(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, paint);", x, y, x + width, y + height);
}
} else if (!hidden && localName.equals("line")) {
Float x1 = getFloatAttr("x1", atts);
Float x2 = getFloatAttr("x2", atts);
Float y1 = getFloatAttr("y1", atts);
Float y2 = getFloatAttr("y2", atts);
Properties props = new Properties(atts);
if (doStroke(props)) {
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
drawInstructions.add("canvas.drawLine(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, paint);", x1, y1, x2, y2);
}
} else if (!hidden && localName.equals("circle")) {
Float centerX = getFloatAttr("cx", atts);
Float centerY = getFloatAttr("cy", atts);
Float radius = getFloatAttr("r", atts);
if (centerX != null && centerY != null && radius != null) {
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
Properties props = new Properties(atts);
if (doFill(props, gradientMap)) {
drawInstructions.add("canvas.drawCircle(factorScale * %ff, factorScale * %ff, factorScale * %ff, paint);", centerX, centerY, radius);
}
if (doStroke(props)) {
drawInstructions.add("canvas.drawCircle(factorScale * %ff, factorScale * %ff, factorScale * %ff, paint);", centerX, centerY, radius);
}
}
} else if (!hidden && localName.equals("ellipse")) {
Float centerX = getFloatAttr("cx", atts);
Float centerY = getFloatAttr("cy", atts);
Float radiusX = getFloatAttr("rx", atts);
Float radiusY = getFloatAttr("ry", atts);
if (centerX != null && centerY != null && radiusX != null && radiusY != null) {
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
Properties props = new Properties(atts);
drawInstructions.add("rect.set(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff);", centerX - radiusX, centerY - radiusY, centerX + radiusX, centerY + radiusY);
if (doFill(props, gradientMap)) {
drawInstructions.add("canvas.drawOval(rect, paint);");
}
if (doStroke(props)) {
drawInstructions.add("canvas.drawOval(rect, paint);");
}
}
} else if (!hidden && (localName.equals("polygon") || localName.equals("polyline"))) {
NumberParse numbers = getNumberParseAttr("points", atts);
if (numbers != null) {
drawInstructions.add("p.reset();");
if (numbers.size() > 1) {
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
Properties props = new Properties(atts);
drawInstructions.add("p.moveTo(factorScale * %ff, factorScale * %ff);", numbers.getNumber(0), numbers.getNumber(1));
for (int i = 2; i < numbers.size(); i += 2) {
float x = numbers.getNumber(i);
float y = numbers.getNumber(i + 1);
drawInstructions.add("p.lineTo(factorScale * %ff, factorScale * %ff);", x, y);
}
// Don't close a polyline
if (localName.equals("polygon")) {
drawInstructions.add("p.close();");
}
if (doFill(props, gradientMap)) {
drawInstructions.add("canvas.drawPath(p, paint);");
}
if (doStroke(props)) {
drawInstructions.add("canvas.drawPath(p, paint);");
}
}
}
} else if (!hidden && localName.equals("path")) {
doPath(drawInstructions, getStringAttr("d", atts));
if (pushTransform(atts)) {
element.setHasCanvasSave();
}
Properties props = new Properties(atts);
if (doFill(props, gradientMap)) {
// doLimits(p);
drawInstructions.add("canvas.drawPath(p, paint);");
}
if (doStroke(props)) {
drawInstructions.add("canvas.drawPath(p, paint);");
}
} else if (!hidden) {
}
}
@Override
public void characters(char ch[], int start, int length) {
// no-op
}
@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
if (localName == null || localName.length() == 0) {
localName = qName;
}
if (localName.equals("svg")) {
} else if (localName.equals("linearGradient")) {
if (gradient.id != null) {
if (gradient.xlink != null) {
Gradient parent = gradientRefMap.get(gradient.xlink);
if (parent != null) {
gradient = parent.createChild(gradient);
}
}
int[] colors = new int[gradient.colors.size()];
for (int i = 0; i < colors.length; i++) {
colors[i] = gradient.colors.get(i);
}
float[] positions = new float[gradient.positions.size()];
for (int i = 0; i < positions.length; i++) {
positions[i] = gradient.positions.get(i);
}
if (colors.length == 0) {
}
LinearGradient g = new LinearGradient(gradient.x1, gradient.y1, gradient.x2, gradient.y2, colors, positions, "Shader.TileMode.CLAMP");
g.setLocalMatrix(gradient.matrixInstructions);
gradientMap.put(gradient.id, g);
gradientRefMap.put(gradient.id, gradient);
}
} else if (localName.equals("radialGradient")) {
if (gradient.id != null) {
if (gradient.xlink != null) {
Gradient parent = gradientRefMap.get(gradient.xlink);
if (parent != null) {
gradient = parent.createChild(gradient);
}
}
int[] colors = new int[gradient.colors.size()];
for (int i = 0; i < colors.length; i++) {
colors[i] = gradient.colors.get(i);
}
float[] positions = new float[gradient.positions.size()];
for (int i = 0; i < positions.length; i++) {
positions[i] = gradient.positions.get(i);
}
if (gradient.xlink != null) {
Gradient parent = gradientRefMap.get(gradient.xlink);
if (parent != null) {
gradient = parent.createChild(gradient);
}
}
RadialGradient g = new RadialGradient(gradient.x, gradient.y, gradient.radius, colors, positions, "Shader.TileMode.CLAMP");
g.setLocalMatrix(gradient.matrixInstructions);
gradientMap.put(gradient.id, g);
gradientRefMap.put(gradient.id, gradient);
}
} else if (localName.equals("g")) {
if (boundsMode) {
boundsMode = false;
}
// Break out of hidden mode
if (hidden) {
hiddenLevel--;
// Util.debug("Hidden down: " + hiddenLevel);
if (hiddenLevel == 0) {
hidden = false;
}
}
// Clear gradient map
gradientMap.clear();
} else if (localName.equals("defs")) {
defsMode = false;
}
Element element = pollLastElement(localName);
if (element != null && element.hasCanvasSave()) {
popTransform();
}
}
private Element pollLastElement(String name) {
if (elements.size() == 0) {
return null;
}
Element element = elements.get(0);
if (element != null && name != null && name.equals(element.getName())) {
elements.remove(0);
return element;
} else {
return null;
}
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/SVGParser.java
================================================
package com.skocken.svgconverter.svg;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
public class SVGParser {
public static void getSVGFromInputStream(String packageName, String className, InputStream svgData) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
SVGHandler handler = new SVGHandler(packageName, className);
xr.setContentHandler(handler);
xr.parse(new InputSource(svgData));
handler.drawInstructions.print();
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/SVGParsingMethods.java
================================================
package com.skocken.svgconverter.svg;
import java.util.ArrayList;
import org.xml.sax.Attributes;
public class SVGParsingMethods {
static NumberParse parseNumbers(String s) {
// Util.debug("Parsing numbers from: '" + s + "'");
int n = s.length();
int p = 0;
ArrayList numbers = new ArrayList();
boolean skipChar = false;
for (int i = 1; i < n; i++) {
if (skipChar) {
skipChar = false;
continue;
}
char c = s.charAt(i);
switch (c) {
// This ends the parsing, as we are on the next element
case 'M':
case 'm':
case 'Z':
case 'z':
case 'L':
case 'l':
case 'H':
case 'h':
case 'V':
case 'v':
case 'C':
case 'c':
case 'S':
case 's':
case 'Q':
case 'q':
case 'T':
case 't':
case 'a':
case 'A':
case ')': {
String str = s.substring(p, i);
if (str.trim().length() > 0) {
// Util.debug(" Last: " + str);
Float f = Float.parseFloat(str);
numbers.add(f);
}
p = i;
return new NumberParse(numbers, p);
}
case '\n':
case '\t':
case ' ':
case ',':
case '-': {
String str = s.substring(p, i);
// Just keep moving if multiple whitespace
if (str.trim().length() > 0) {
// Util.debug(" Next: " + str);
Float f = Float.parseFloat(str);
numbers.add(f);
if (c == '-') {
p = i;
} else {
p = i + 1;
skipChar = true;
}
} else {
p++;
}
break;
}
}
}
String last = s.substring(p);
if (last.length() > 0) {
// Util.debug(" Last: " + last);
try {
numbers.add(Float.parseFloat(last));
} catch (NumberFormatException nfe) {
// Just white-space, forget it
}
p = s.length();
}
return new NumberParse(numbers, p);
}
static InstructionRecorder parseTransform(InstructionRecorder drawInstructions, String s) {
drawInstructions.add("matrix.reset();");
return parseTransformInternal(drawInstructions, s);
}
static InstructionRecorder parseTransformInternal(InstructionRecorder drawInstructions, String s) {
int lastP = s.lastIndexOf("(");
if (lastP > -1) {
String left = s.substring(0, lastP).trim();
NumberParse np = parseNumbers(s.substring(lastP + 1));
if (left.endsWith("matrix") && np.size() == 6) {
// matrix
drawInstructions.add("matrix.setValues(new float[]{ factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, 0, 0, factorScale});",
// Row 1
np.getNumber(0), np.getNumber(2), np.getNumber(4),
// Row 2
np.getNumber(1), np.getNumber(3), np.getNumber(5));
} else if (left.endsWith("translate") && np.size() > 0) {
// translate
float tx = np.getNumber(0);
float ty = 0;
if (np.size() > 1) {
ty = np.getNumber(1);
}
drawInstructions.add("matrix.postTranslate(factorScale * %ff, factorScale * %ff);", tx, ty);
} else if (left.endsWith("scale") && np.size() > 0) {
float sx = np.getNumber(0);
float sy = 0;
if (np.size() > 1) {
sy = np.getNumber(1);
}
drawInstructions.add("matrix.postScale(%ff, %ff);", sx, sy);
} else if (left.endsWith("skewX") && np.size() > 0) {
float angle = np.getNumber(0);
drawInstructions.add("matrix.postSkew(%ff, 0);", (float) Math.tan(angle));
} else if (left.endsWith("skewY") && np.size() > 0) {
float angle = np.getNumber(0);
drawInstructions.add("matrix.postSkew(0, %ff);", (float) Math.tan(angle));
} else if (left.endsWith("rotate") && np.size() > 0) {
float angle = np.getNumber(0);
float cx = 0;
float cy = 0;
if (np.size() > 2) {
cx = np.getNumber(1);
cy = np.getNumber(2);
}
if (cx != 0 || cy != 0) {
drawInstructions.add("matrix.postTranslate(factorScale * %ff, factorScale * %ff);", cx, cy);
}
drawInstructions.add("matrix.postRotate(%ff);", angle);
if (cx != 0 || cy != 0) {
drawInstructions.add("matrix.postTranslate(factorScale * %ff, factorScale * %ff);", -cx, -cy);
}
}
parseTransformInternal(drawInstructions, left);
}
return drawInstructions;
}
/**
* This is where the hard-to-parse paths are handled.
* Uppercase rules are absolute positions, lowercase are relative.
* Types of path rules:
*
*
* - M/m - (x y)+ - Move to (without drawing)
*
- Z/z - (no params) - Close path (back to starting point)
*
- L/l - (x y)+ - Line to
*
- H/h - x+ - Horizontal ine to
*
- V/v - y+ - Vertical line to
*
- C/c - (x1 y1 x2 y2 x y)+ - Cubic bezier to
*
- S/s - (x2 y2 x y)+ - Smooth cubic bezier to (shorthand that assumes the x2, y2 from previous C/S is the x1, y1 of this bezier)
*
- Q/q - (x1 y1 x y)+ - Quadratic bezier to
*
- T/t - (x y)+ - Smooth quadratic bezier to (assumes previous control point is "reflection" of last one w.r.t. to current point)
*
*
* Numbers are separate by whitespace, comma or nothing at all (!) if they are self-delimiting, (ie. begin with a - sign)
*
* @param s
* the path string from the XML
*/
static void doPath(InstructionRecorder drawInstructions, String s) {
int n = s.length();
ParserHelper ph = new ParserHelper(s, 0);
ph.skipWhitespace();
drawInstructions.add("p.reset();");
float lastX = 0;
float lastY = 0;
float lastX1 = 0;
float lastY1 = 0;
float subPathStartX = 0;
float subPathStartY = 0;
int nbMove = 0;
char prevCmd = 0;
while (ph.pos < n) {
char cmd = s.charAt(ph.pos);
switch (cmd) {
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (prevCmd == 'm' || prevCmd == 'M') {
cmd = (char) (((int) prevCmd) - 1);
break;
} else if (prevCmd == 'c' || prevCmd == 'C') {
cmd = prevCmd;
break;
} else if (prevCmd == 'l' || prevCmd == 'L') {
cmd = prevCmd;
break;
}
default: {
ph.advance();
prevCmd = cmd;
}
}
boolean wasCurve = false;
switch (cmd) {
case 'M':
case 'm': {
nbMove++;
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'm') {
subPathStartX += x;
subPathStartY += y;
drawInstructions.add("p.rMoveTo(factorScale * %ff, factorScale * %ff);", x, y);
lastX += x;
lastY += y;
} else {
subPathStartX = x;
subPathStartY = y;
drawInstructions.add("p.moveTo(factorScale * %ff, factorScale * %ff);", x, y);
lastX = x;
lastY = y;
}
break;
}
case 'Z':
case 'z': {
drawInstructions.add("p.close();");
drawInstructions.add("p.moveTo(factorScale * %ff, factorScale * %ff);", subPathStartX, subPathStartY);
lastX = subPathStartX;
lastY = subPathStartY;
lastX1 = subPathStartX;
lastY1 = subPathStartY;
wasCurve = true;
break;
}
case 'L':
case 'l': {
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'l') {
drawInstructions.add("p.rLineTo(factorScale * %ff, factorScale * %ff);", x, y);
lastX += x;
lastY += y;
} else {
drawInstructions.add("p.lineTo(factorScale * %ff, factorScale * %ff);", x, y);
lastX = x;
lastY = y;
}
break;
}
case 'H':
case 'h': {
float x = ph.nextFloat();
if (cmd == 'h') {
drawInstructions.add("p.rLineTo(factorScale * %ff, 0);", x);
lastX += x;
} else {
drawInstructions.add("p.lineTo(factorScale * %ff, factorScale * %ff);", x, lastY);
lastX = x;
}
break;
}
case 'V':
case 'v': {
float y = ph.nextFloat();
if (cmd == 'v') {
drawInstructions.add("p.rLineTo(0, factorScale * %ff);", y);
lastY += y;
} else {
drawInstructions.add("p.lineTo(factorScale * %ff, factorScale * %ff);", lastX, y);
lastY = y;
}
break;
}
case 'C':
case 'c': {
wasCurve = true;
float x1 = ph.nextFloat();
float y1 = ph.nextFloat();
float x2 = ph.nextFloat();
float y2 = ph.nextFloat();
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 'c') {
drawInstructions.add("p.rCubicTo(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff);", x1, y1, x2, y2, x, y);
lastX1 += x2;
lastY1 += y2;
lastX += x;
lastY += y;
} else {
drawInstructions.add("p.cubicTo(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff);", x1, y1, x2, y2, x, y);
lastX1 = x2;
lastY1 = y2;
lastX = x;
lastY = y;
}
break;
}
case 'S':
case 's': {
wasCurve = true;
float x2 = ph.nextFloat();
float y2 = ph.nextFloat();
float x = ph.nextFloat();
float y = ph.nextFloat();
if (cmd == 's') {
x2 += lastX;
x += lastX;
y2 += lastY;
y += lastY;
}
float x1 = 2 * lastX - lastX1;
float y1 = 2 * lastY - lastY1;
drawInstructions.add("p.cubicTo(factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff, factorScale * %ff);", x1, y1, x2, y2, x, y);
lastX1 = x2;
lastY1 = y2;
lastX = x;
lastY = y;
break;
}
case 'A':
case 'a': {
float rx = ph.nextFloat();
float ry = ph.nextFloat();
float theta = ph.nextFloat();
int largeArc = (int) ph.nextFloat();
int sweepArc = (int) ph.nextFloat();
float x = ph.nextFloat();
float y = ph.nextFloat();
drawArc(drawInstructions, lastX, lastY, x, y, rx, ry, theta, largeArc, sweepArc);
lastX = x;
lastY = y;
break;
}
}
if (!wasCurve) {
lastX1 = lastX;
lastY1 = lastY;
}
ph.skipWhitespace();
}
if (nbMove > 1) {
drawInstructions.add("p.setFillType(Path.FillType.EVEN_ODD);");
}
}
static void drawArc(InstructionRecorder drawInstructions, float lastX, float lastY, float x, float y, float rx, float ry, float theta, int largeArc, int sweepArc) {
// todo - not implemented yet, may be very hard to do using Android drawing facilities.
}
static NumberParse getNumberParseAttr(String name, Attributes attributes) {
int n = attributes.getLength();
for (int i = 0; i < n; i++) {
if (attributes.getLocalName(i).equals(name)) {
return parseNumbers(attributes.getValue(i));
}
}
return null;
}
static String getStringAttr(String name, Attributes attributes) {
int n = attributes.getLength();
for (int i = 0; i < n; i++) {
if (attributes.getLocalName(i).equals(name)) {
return attributes.getValue(i);
}
}
return null;
}
static Float getFloatAttr(String name, Attributes attributes) {
return getFloatAttr(name, attributes, null);
}
static Float getFloatAttr(String name, Attributes attributes, Float defaultValue) {
String v = getStringAttr(name, attributes);
if (v == null) {
return defaultValue;
} else {
if (v.endsWith("px")) {
v = v.substring(0, v.length() - 2);
}
// Log.d(TAG, "Float parsing '" + name + "=" + v + "'");
return Float.parseFloat(v);
}
}
static Integer getHexAttr(String name, Attributes attributes) {
String v = getStringAttr(name, attributes);
// Util.debug("Hex parsing '" + name + "=" + v + "'");
if (v == null) {
return null;
} else {
try {
return Integer.parseInt(v.substring(1), 16);
} catch (NumberFormatException nfe) {
// todo - parse word-based color here
return null;
}
}
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/Shader.java
================================================
package com.skocken.svgconverter.svg;
public abstract class Shader {
private InstructionRecorder matrixInstructions;
public abstract void printTo(InstructionRecorder drawInstructions);
protected void printMatrixTo(InstructionRecorder drawInstructions) {
if (matrixInstructions == null || matrixInstructions.isEmpty()) {
return;
}
drawInstructions.add(matrixInstructions);
drawInstructions.add("shader.setLocalMatrix(matrix);");
}
public void setLocalMatrix(InstructionRecorder matrixInstructions) {
this.matrixInstructions = matrixInstructions;
}
}
================================================
FILE: src/com/skocken/svgconverter/svg/StyleSet.java
================================================
package com.skocken.svgconverter.svg;
import java.util.HashMap;
public class StyleSet {
HashMap styleMap = new HashMap();
StyleSet(String string) {
String[] styles = string.split(";");
for (String s : styles) {
String[] style = s.split(":");
if (style.length == 2) {
styleMap.put(style[0], style[1]);
}
}
}
public String getStyle(String name) {
return styleMap.get(name);
}
}