private void parseAnchor(String anchor) { Map<String, Float> keywords = new HashMap<>(); keywords.put("centre", 0.5f); keywords.put("center", 0.5f); keywords.put("middle", 0.5f); keywords.put("mid", 0.5f); keywords.put("left", 0.0f); keywords.put("right", 1.0f); keywords.put("top", 0.0f); keywords.put("bottom", 1.0f); float x, y; String[] words = anchor.split(" "); switch (words.length) { case 1: if (words[0].contains("%")) { setAnchorX(MathUtil.numeralPercentage(words[0], getDestinationWidth())); setAnchorY(MathUtil.numeralPercentage(words[0], getDestinationHeight())); } break; case 2: if (words[0].contains("%")) { setAnchorX(MathUtil.numeralPercentage(words[0], getDestinationWidth())); } else { if (NumberUtils.isNumber(words[0])) { setAnchorX(Short.parseShort(words[0])); } else { if (keywords.containsKey(words[0])) { setAnchorX((short) (getDestinationWidth() * keywords.get(words[0]))); } else { setAnchorX((short) 0); } } } if (words[1].contains("%")) { setAnchorY(MathUtil.numeralPercentage(words[1], getDestinationHeight())); } else { if (NumberUtils.isNumber(words[1])) { setAnchorY(Short.parseShort(words[1])); } else { if (keywords.containsKey(words[1])) { setAnchorY((short) (getDestinationHeight() * keywords.get(words[1]))); } else { setAnchorY((short) 0); } } } break; default: setAnchorX((short) 0); setAnchorY((short) 0); } }
@Override public boolean readFromJSON(JSONObject component) { // Required values try { setName(component.getString("name")); setSource(component.getString("src-img")); setDestinationWidth((short) component.getInt("dest-w")); setDestinationHeight((short) component.getInt("dest-h")); } catch (JSONException e) { System.err.println("A required value was missing in one of your sprites."); System.err.println( "Required values: \n name <string>\n src-img <string>\n dest-w <number>\n dest-h <number>"); System.err.println("If all values exist, make sure that they are valid and non-zero."); return false; } try { setSourceWidth( component.has("src-w") ? (short) component.getInt("src-w") : getDestinationWidth()); setSourceHeight( component.has("src-h") ? (short) component.getInt("src-h") : getDestinationHeight()); setSourceX(component.has("src-x") ? (short) component.getInt("src-x") : (short) 0); setSourceY(component.has("src-y") ? (short) component.getInt("src-y") : (short) 0); if (component.has("anchor")) { parseAnchor(component.getString("anchor")); } else { setAnchorX( component.has("anchor-x") ? MathUtil.numeralPercentage(component.getString("anchor-x"), getDestinationWidth()) : (short) 0); setAnchorY( component.has("anchor-y") ? MathUtil.numeralPercentage( component.getString("anchor-y"), getDestinationHeight()) : (short) 0); } } catch (JSONException e) { System.err.println( "One or more of the values you supplied were not valid. Please refer to the specification.\n"); e.printStackTrace(); } return true; }