diff --git a/android/src/main/java/com/horcrux/svg/Brush.java b/android/src/main/java/com/horcrux/svg/Brush.java index 1d0a24534..6ca031292 100644 --- a/android/src/main/java/com/horcrux/svg/Brush.java +++ b/android/src/main/java/com/horcrux/svg/Brush.java @@ -9,6 +9,9 @@ package com.horcrux.svg; +import android.graphics.Bitmap; +import android.graphics.BitmapShader; +import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Matrix; @@ -23,12 +26,14 @@ import com.facebook.react.common.ReactConstants; class Brush { - private BrushType mType = BrushType.LINEAR_GRADIENT; + private BrushType mType; private final ReadableArray mPoints; private ReadableArray mColors; private final boolean mUseObjectBoundingBox; + private boolean mUseContentObjectBoundingBox; private Matrix mMatrix; private Rect mUserSpaceBoundingBox; + PatternShadowNode mPattern; Brush(BrushType type, ReadableArray points, BrushUnits units) { mType = type; @@ -36,6 +41,14 @@ class Brush { mUseObjectBoundingBox = units == BrushUnits.OBJECT_BOUNDING_BOX; } + void setContentUnits(BrushUnits units) { + mUseContentObjectBoundingBox = units == BrushUnits.OBJECT_BOUNDING_BOX; + } + + void setPattern(PatternShadowNode pattern) { + mPattern = pattern; + } + enum BrushType { LINEAR_GRADIENT(0), RADIAL_GRADIENT(1), @@ -105,6 +118,35 @@ void setupPaint(Paint paint, RectF pathBoundingBox, float scale, float opacity) float offsetX = rect.left; float offsetY = rect.top; + if (mType == BrushType.PATTERN) { + double x = PropHelper.fromRelative(mPoints.getString(0), width, offsetX, scale, paint.getTextSize()); + double y = PropHelper.fromRelative(mPoints.getString(1), height, offsetY, scale, paint.getTextSize()); + double w = PropHelper.fromRelative(mPoints.getString(2), width, offsetX, scale, paint.getTextSize()); + double h = PropHelper.fromRelative(mPoints.getString(3), height, offsetY, scale, paint.getTextSize()); + + RectF vbRect = mPattern.getViewBox(); + RectF eRect = new RectF((float)x, (float)y, (float)w, (float)h); + Matrix mViewBoxMatrix = ViewBox.getTransform(vbRect, eRect, mPattern.mAlign, mPattern.mMeetOrSlice); + + Bitmap bitmap = Bitmap.createBitmap( + (int) w, + (int) h, + Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + canvas.concat(mViewBoxMatrix); + mPattern.draw(canvas, new Paint(), opacity); + + Matrix patternMatrix = new Matrix(); + if (mMatrix != null) { + patternMatrix.preConcat(mMatrix); + } + + BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); + bitmapShader.setLocalMatrix(patternMatrix); + paint.setShader(bitmapShader); + return; + } + int stopsCount = mColors.size() / 5; int[] stopsColors = new int[stopsCount]; float[] stops = new float[stopsCount]; @@ -170,12 +212,5 @@ void setupPaint(Paint paint, RectF pathBoundingBox, float scale, float opacity) radialGradient.setLocalMatrix(radialMatrix); paint.setShader(radialGradient); } - // else { - // todo: pattern support - - //Shader mShader1 = new BitmapShader(bitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); - //paint.setShader(mShader1); - //bitmap.recycle(); - // } } } diff --git a/android/src/main/java/com/horcrux/svg/GroupShadowNode.java b/android/src/main/java/com/horcrux/svg/GroupShadowNode.java index 351c1eb67..d2e120cfe 100644 --- a/android/src/main/java/com/horcrux/svg/GroupShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/GroupShadowNode.java @@ -10,9 +10,14 @@ package com.horcrux.svg; import android.graphics.Canvas; +import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; +import android.graphics.Rect; import android.graphics.RectF; +import android.graphics.Region; +import android.os.Build; +import android.support.annotation.RequiresApi; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.uimanager.ReactShadowNode; @@ -79,7 +84,7 @@ public void run(ReactShadowNode lNode) { } int count = node.saveAndSetupCanvas(canvas); - node.draw(canvas, paint, opacity * mOpacity); + node.render(canvas, paint, opacity * mOpacity); RectF r = node.getClientRect(); if (r != null) { groupRect.union(r); @@ -119,7 +124,9 @@ protected Path getPath(final Canvas canvas, final Paint paint) { traverseChildren(new NodeRunnable() { public void run(ReactShadowNode node) { if (node instanceof VirtualNode) { - path.addPath(((VirtualNode)node).getPath(canvas, paint)); + VirtualNode n = (VirtualNode)node; + Matrix transform = n.mMatrix; + path.addPath(n.getPath(canvas, paint), transform); } } }); @@ -127,6 +134,56 @@ public void run(ReactShadowNode node) { return path; } + protected Path getPath(final Canvas canvas, final Paint paint, final Region.Op op) { + final Path path = new Path(); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + final Path.Op pop = Path.Op.valueOf(op.name()); + traverseChildren(new NodeRunnable() { + @RequiresApi(api = Build.VERSION_CODES.KITKAT) + public void run(ReactShadowNode node) { + if (node instanceof VirtualNode) { + VirtualNode n = (VirtualNode)node; + Matrix transform = n.mMatrix; + Path p2; + if (n instanceof GroupShadowNode) { + p2 = ((GroupShadowNode)n).getPath(canvas, paint, op); + } else { + p2 = n.getPath(canvas, paint); + } + p2.transform(transform); + path.op(p2, pop); + } + } + }); + } else { + Rect clipBounds = canvas.getClipBounds(); + final Region bounds = new Region(clipBounds); + final Region r = new Region(); + traverseChildren(new NodeRunnable() { + public void run(ReactShadowNode node) { + if (node instanceof VirtualNode) { + VirtualNode n = (VirtualNode)node; + Matrix transform = n.mMatrix; + Path p2; + if (n instanceof GroupShadowNode) { + p2 = ((GroupShadowNode)n).getPath(canvas, paint, op); + } else { + p2 = n.getPath(canvas, paint); + } + p2.transform(transform); + Region r2 = new Region(); + r2.setPath(p2, bounds); + r.op(r2, op); + } + } + }); + path.addPath(r.getBoundaryPath()); + } + + return path; + } + @Override public int hitTest(final float[] src) { if (!mInvertible) { diff --git a/android/src/main/java/com/horcrux/svg/ImageShadowNode.java b/android/src/main/java/com/horcrux/svg/ImageShadowNode.java index 287ae3570..e1b48dec3 100644 --- a/android/src/main/java/com/horcrux/svg/ImageShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/ImageShadowNode.java @@ -77,13 +77,13 @@ public void setY(String y) { markUpdated(); } - @ReactProp(name = "width") + @ReactProp(name = "imagewidth") public void setWidth(String width) { mW = width; markUpdated(); } - @ReactProp(name = "height") + @ReactProp(name = "imageheight") public void seHeight(String height) { mH = height; markUpdated(); diff --git a/android/src/main/java/com/horcrux/svg/MaskShadowNode.java b/android/src/main/java/com/horcrux/svg/MaskShadowNode.java new file mode 100644 index 000000000..063041118 --- /dev/null +++ b/android/src/main/java/com/horcrux/svg/MaskShadowNode.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ + + +package com.horcrux.svg; + +import android.graphics.Matrix; + +import com.facebook.common.logging.FLog; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.common.ReactConstants; +import com.facebook.react.uimanager.annotations.ReactProp; + +import javax.annotation.Nullable; + +/** + * Shadow node for virtual Mask definition view + */ +class MaskShadowNode extends GroupShadowNode { + + String mX; + String mY; + String mWidth; + String mHeight; + Brush.BrushUnits mMaskUnits; + Brush.BrushUnits mMaskContentUnits; + + private static final float[] sRawMatrix = new float[]{ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + }; + private Matrix mMatrix = null; + + @ReactProp(name = "x") + public void setX(String x) { + mX = x; + markUpdated(); + } + + @ReactProp(name = "y") + public void setY(String y) { + mY = y; + markUpdated(); + } + + @ReactProp(name = "maskwidth") + public void setWidth(String width) { + mWidth = width; + markUpdated(); + } + + @ReactProp(name = "maskheight") + public void setHeight(String height) { + mHeight = height; + markUpdated(); + } + + @ReactProp(name = "maskUnits") + public void setMaskUnits(int maskUnits) { + switch (maskUnits) { + case 0: + mMaskUnits = Brush.BrushUnits.OBJECT_BOUNDING_BOX; + break; + case 1: + mMaskUnits = Brush.BrushUnits.USER_SPACE_ON_USE; + break; + } + markUpdated(); + } + + @ReactProp(name = "maskContentUnits") + public void setMaskContentUnits(int maskContentUnits) { + switch (maskContentUnits) { + case 0: + mMaskContentUnits = Brush.BrushUnits.OBJECT_BOUNDING_BOX; + break; + case 1: + mMaskContentUnits = Brush.BrushUnits.USER_SPACE_ON_USE; + break; + } + markUpdated(); + } + + @ReactProp(name = "maskTransform") + public void setMaskTransform(@Nullable ReadableArray matrixArray) { + if (matrixArray != null) { + int matrixSize = PropHelper.toMatrixData(matrixArray, sRawMatrix, mScale); + if (matrixSize == 6) { + if (mMatrix == null) { + mMatrix = new Matrix(); + } + mMatrix.setValues(sRawMatrix); + } else if (matrixSize != -1) { + FLog.w(ReactConstants.TAG, "RNSVG: Transform matrices must be of size 6"); + } + } else { + mMatrix = null; + } + + markUpdated(); + } + + @Override + protected void saveDefinition() { + if (mName != null) { + SvgViewShadowNode svg = getSvgShadowNode(); + svg.defineMask(this, mName); + } + } +} diff --git a/android/src/main/java/com/horcrux/svg/PatternShadowNode.java b/android/src/main/java/com/horcrux/svg/PatternShadowNode.java new file mode 100644 index 000000000..92eda0ae1 --- /dev/null +++ b/android/src/main/java/com/horcrux/svg/PatternShadowNode.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ + + +package com.horcrux.svg; + +import android.graphics.Matrix; +import android.graphics.RectF; + +import com.facebook.common.logging.FLog; +import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.bridge.WritableArray; +import com.facebook.react.common.ReactConstants; +import com.facebook.react.uimanager.annotations.ReactProp; + +import javax.annotation.Nullable; + +/** + * Shadow node for virtual Pattern definition view + */ +class PatternShadowNode extends GroupShadowNode { + + private String mX; + private String mY; + private String mWidth; + private String mHeight; + private Brush.BrushUnits mPatternUnits; + private Brush.BrushUnits mPatternContentUnits; + + private float mMinX; + private float mMinY; + private float mVbWidth; + private float mVbHeight; + String mAlign; + int mMeetOrSlice; + + private static final float[] sRawMatrix = new float[]{ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + }; + private Matrix mMatrix = null; + + @ReactProp(name = "x") + public void setX(String x) { + mX = x; + markUpdated(); + } + + @ReactProp(name = "y") + public void setY(String y) { + mY = y; + markUpdated(); + } + + @ReactProp(name = "patternwidth") + public void setWidth(String width) { + mWidth = width; + markUpdated(); + } + + @ReactProp(name = "patternheight") + public void setHeight(String height) { + mHeight = height; + markUpdated(); + } + + @ReactProp(name = "patternUnits") + public void setPatternUnits(int patternUnits) { + switch (patternUnits) { + case 0: + mPatternUnits = Brush.BrushUnits.OBJECT_BOUNDING_BOX; + break; + case 1: + mPatternUnits = Brush.BrushUnits.USER_SPACE_ON_USE; + break; + } + markUpdated(); + } + + @ReactProp(name = "patternContentUnits") + public void setPatternContentUnits(int patternContentUnits) { + switch (patternContentUnits) { + case 0: + mPatternContentUnits = Brush.BrushUnits.OBJECT_BOUNDING_BOX; + break; + case 1: + mPatternContentUnits = Brush.BrushUnits.USER_SPACE_ON_USE; + break; + } + markUpdated(); + } + + @ReactProp(name = "patternTransform") + public void setPatternTransform(@Nullable ReadableArray matrixArray) { + if (matrixArray != null) { + int matrixSize = PropHelper.toMatrixData(matrixArray, sRawMatrix, mScale); + if (matrixSize == 6) { + if (mMatrix == null) { + mMatrix = new Matrix(); + } + mMatrix.setValues(sRawMatrix); + } else if (matrixSize != -1) { + FLog.w(ReactConstants.TAG, "RNSVG: Transform matrices must be of size 6"); + } + } else { + mMatrix = null; + } + + markUpdated(); + } + + @ReactProp(name = "minX") + public void setMinX(float minX) { + mMinX = minX; + markUpdated(); + } + + @ReactProp(name = "minY") + public void setMinY(float minY) { + mMinY = minY; + markUpdated(); + } + + @ReactProp(name = "vbWidth") + public void setVbWidth(float vbWidth) { + mVbWidth = vbWidth; + markUpdated(); + } + + @ReactProp(name = "vbHeight") + public void setVbHeight(float vbHeight) { + mVbHeight = vbHeight; + markUpdated(); + } + + @ReactProp(name = "align") + public void setAlign(String align) { + mAlign = align; + markUpdated(); + } + + @ReactProp(name = "meetOrSlice") + public void setMeetOrSlice(int meetOrSlice) { + mMeetOrSlice = meetOrSlice; + markUpdated(); + } + + + RectF getViewBox() { + return new RectF(mMinX * mScale, mMinY * mScale, (mMinX + mVbWidth) * mScale, (mMinY + mVbHeight) * mScale); + } + + @Override + protected void saveDefinition() { + if (mName != null) { + WritableArray points = Arguments.createArray(); + points.pushString(mX); + points.pushString(mY); + points.pushString(mWidth); + points.pushString(mHeight); + + Brush brush = new Brush(Brush.BrushType.PATTERN, points, mPatternUnits); + brush.setContentUnits(mPatternContentUnits); + brush.setPattern(this); + + if (mMatrix != null) { + brush.setGradientTransform(mMatrix); + } + + SvgViewShadowNode svg = getSvgShadowNode(); + if (mPatternUnits == Brush.BrushUnits.USER_SPACE_ON_USE || mPatternContentUnits == Brush.BrushUnits.USER_SPACE_ON_USE) { + brush.setUserSpaceBoundingBox(svg.getCanvasBounds()); + } + + svg.defineBrush(brush, mName); + } + } +} diff --git a/android/src/main/java/com/horcrux/svg/RectShadowNode.java b/android/src/main/java/com/horcrux/svg/RectShadowNode.java index cbd27917d..35a7a1e49 100644 --- a/android/src/main/java/com/horcrux/svg/RectShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/RectShadowNode.java @@ -40,14 +40,14 @@ public void setY(String y) { markUpdated(); } - @ReactProp(name = "width") + @ReactProp(name = "rectwidth") public void setWidth(String width) { mW = width; markUpdated(); } - @ReactProp(name = "height") + @ReactProp(name = "rectheight") public void setHeight(String height) { mH = height; markUpdated(); diff --git a/android/src/main/java/com/horcrux/svg/RenderableShadowNode.java b/android/src/main/java/com/horcrux/svg/RenderableShadowNode.java index b61d7ad84..2a1c17486 100644 --- a/android/src/main/java/com/horcrux/svg/RenderableShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/RenderableShadowNode.java @@ -9,20 +9,24 @@ package com.horcrux.svg; +import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.DashPathEffect; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffXfermode; +import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; +import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; +import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.uimanager.OnLayoutEvent; -import com.facebook.react.uimanager.UIManagerModule; +import com.facebook.react.bridge.ReadableType; import com.facebook.react.uimanager.annotations.ReactProp; -import com.facebook.react.uimanager.events.EventDispatcher; import java.lang.reflect.Field; import java.util.ArrayList; @@ -39,17 +43,17 @@ abstract public class RenderableShadowNode extends VirtualNode { // strokeLinecap private static final int CAP_BUTT = 0; - private static final int CAP_ROUND = 1; + static final int CAP_ROUND = 1; private static final int CAP_SQUARE = 2; // strokeLinejoin private static final int JOIN_BEVEL = 2; private static final int JOIN_MITER = 0; - private static final int JOIN_ROUND = 1; + static final int JOIN_ROUND = 1; // fillRule private static final int FILL_RULE_EVENODD = 0; - private static final int FILL_RULE_NONZERO = 1; + static final int FILL_RULE_NONZERO = 1; public @Nullable ReadableArray mStroke; public @Nullable String[] mStrokeDasharray; @@ -71,9 +75,29 @@ abstract public class RenderableShadowNode extends VirtualNode { protected @Nullable ArrayList mPropList; protected @Nullable ArrayList mAttributeList; + static final Pattern regex = Pattern.compile("[0-9.-]+"); + @ReactProp(name = "fill") - public void setFill(@Nullable ReadableArray fill) { - mFill = fill; + public void setFill(@Nullable Dynamic fill) { + if (fill == null || fill.isNull()) { + mFill = null; + markUpdated(); + return; + } + ReadableType type = fill.getType(); + if (type.equals(ReadableType.Array)) { + mFill = fill.asArray(); + } else { + JavaOnlyArray arr = new JavaOnlyArray(); + arr.pushInt(0); + Matcher m = regex.matcher(fill.asString()); + int i = 0; + while (m.find()) { + Double parsed = Double.parseDouble(m.group()); + arr.pushDouble(i++ < 3 ? parsed / 255 : parsed); + } + mFill = arr; + } markUpdated(); } @@ -100,8 +124,25 @@ public void setFillRule(int fillRule) { } @ReactProp(name = "stroke") - public void setStroke(@Nullable ReadableArray strokeColors) { - mStroke = strokeColors; + public void setStroke(@Nullable Dynamic strokeColors) { + if (strokeColors == null || strokeColors.isNull()) { + mStroke = null; + markUpdated(); + return; + } + ReadableType type = strokeColors.getType(); + if (type.equals(ReadableType.Array)) { + mStroke = strokeColors.asArray(); + } else { + JavaOnlyArray arr = new JavaOnlyArray(); + arr.pushInt(0); + Matcher m = regex.matcher(strokeColors.asString()); + while (m.find()) { + Double parsed = Double.parseDouble(m.group()); + arr.pushDouble(parsed); + } + mStroke = arr; + } markUpdated(); } @@ -126,8 +167,8 @@ public void setStrokeDasharray(@Nullable ReadableArray strokeDasharray) { } @ReactProp(name = "strokeDashoffset") - public void setStrokeDashoffset(float strokeWidth) { - mStrokeDashoffset = strokeWidth * mScale; + public void setStrokeDashoffset(float strokeDashoffset) { + mStrokeDashoffset = strokeDashoffset * mScale; markUpdated(); } @@ -194,6 +235,73 @@ public void setPropList(@Nullable ReadableArray propList) { markUpdated(); } + static double saturate(double v) { + return v <= 0 ? 0 : (v >= 1 ? 1 : v); + } + + public void render(Canvas canvas, Paint paint, float opacity) { + if (mMask != null) { + SvgViewShadowNode root = getSvgShadowNode(); + MaskShadowNode mask = (MaskShadowNode) root.getDefinedMask(mMask); + + Rect clipBounds = canvas.getClipBounds(); + int height = clipBounds.height(); + int width = clipBounds.width(); + + Bitmap maskBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + Bitmap original = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + + Canvas originalCanvas = new Canvas(original); + Canvas maskCanvas = new Canvas(maskBitmap); + Canvas resultCanvas = new Canvas(result); + + // Clip to mask bounds and render the mask + float maskX = (float) relativeOnWidth(mask.mX); + float maskY = (float) relativeOnWidth(mask.mY); + float maskWidth = (float) relativeOnWidth(mask.mWidth); + float maskHeight = (float) relativeOnWidth(mask.mHeight); + maskCanvas.clipRect(maskX, maskY, maskWidth, maskHeight); + + Paint maskpaint = new Paint(Paint.ANTI_ALIAS_FLAG); + mask.draw(maskCanvas, maskpaint, 1); + + // Apply luminanceToAlpha filter primitive https://www.w3.org/TR/SVG11/filters.html#feColorMatrixElement + int nPixels = width * height; + int[] pixels = new int[nPixels]; + maskBitmap.getPixels(pixels, 0, width, 0, 0, width, height); + + for (int i = 0; i < nPixels; i++) { + int color = pixels[i]; + + int r = (color >> 16) & 0xFF; + int g = (color >> 8) & 0xFF; + int b = color & 0xFF; + int a = color >>> 24; + + double luminance = saturate(((0.299 * r) + (0.587 * g) + (0.144 * b)) / 255); + int alpha = (int) (a * luminance); + int pixel = (alpha << 24); + pixels[i] = pixel; + } + + maskBitmap.setPixels(pixels, 0, width, 0, 0, width, height); + + // Render content of current SVG Renderable to image + draw(originalCanvas, paint, opacity); + + // Blend current element and mask + maskpaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); + resultCanvas.drawBitmap(original, 0, 0, null); + resultCanvas.drawBitmap(maskBitmap, 0, 0, maskpaint); + + // Render blended result into current render context + canvas.drawBitmap(result, 0, 0, paint); + } else { + draw(canvas, paint, opacity); + } + } + @Override public void draw(Canvas canvas, Paint paint, float opacity) { opacity *= mOpacity; @@ -203,9 +311,10 @@ public void draw(Canvas canvas, Paint paint, float opacity) { mPath = getPath(canvas, paint); mPath.setFillType(mFillRule); } + Path path = mPath; RectF clientRect = new RectF(); - mPath.computeBounds(clientRect, true); + path.computeBounds(clientRect, true); Matrix svgToViewMatrix = new Matrix(canvas.getMatrix()); svgToViewMatrix.mapRect(clientRect); this.setClientRect(clientRect); @@ -213,10 +322,10 @@ public void draw(Canvas canvas, Paint paint, float opacity) { clip(canvas, paint); if (setupFillPaint(paint, opacity * mFillOpacity)) { - canvas.drawPath(mPath, paint); + canvas.drawPath(path, paint); } if (setupStrokePaint(paint, opacity * mStrokeOpacity)) { - canvas.drawPath(mPath, paint); + canvas.drawPath(path, paint); } } } diff --git a/android/src/main/java/com/horcrux/svg/RenderableView.java b/android/src/main/java/com/horcrux/svg/RenderableView.java new file mode 100644 index 000000000..5c8d13e75 --- /dev/null +++ b/android/src/main/java/com/horcrux/svg/RenderableView.java @@ -0,0 +1,28 @@ +package com.horcrux.svg; + +import android.view.ViewGroup; + +import com.facebook.react.bridge.ReactContext; + +public class RenderableView extends ViewGroup { + public T shadowNode; + + public RenderableView(ReactContext reactContext) { + super(reactContext); + } + + @Override + public void setId(int id) { + super.setId(id); + shadowNode = (T) RenderableViewManager.getShadowNodeByTag(id); + } + + void dropView() { + shadowNode = null; + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + + } +} diff --git a/android/src/main/java/com/horcrux/svg/RenderableViewManager.java b/android/src/main/java/com/horcrux/svg/RenderableViewManager.java index 4ecc38d5e..3b8b07b65 100644 --- a/android/src/main/java/com/horcrux/svg/RenderableViewManager.java +++ b/android/src/main/java/com/horcrux/svg/RenderableViewManager.java @@ -9,18 +9,28 @@ package com.horcrux.svg; -import android.view.View; +import android.util.SparseArray; +import com.facebook.react.bridge.Dynamic; +import com.facebook.react.bridge.ReadableArray; +import com.facebook.react.bridge.ReadableMap; import com.facebook.react.uimanager.LayoutShadowNode; import com.facebook.react.uimanager.ThemedReactContext; -import com.facebook.react.uimanager.ViewManager; +import com.facebook.react.uimanager.ViewGroupManager; +import com.facebook.react.uimanager.annotations.ReactProp; + +import javax.annotation.Nullable; + +import static com.horcrux.svg.RenderableShadowNode.CAP_ROUND; +import static com.horcrux.svg.RenderableShadowNode.FILL_RULE_NONZERO; +import static com.horcrux.svg.RenderableShadowNode.JOIN_ROUND; /** * ViewManager for all shadowed RNSVG views: Group, Path and Text. Since these never get rendered * into native views and don't need any logic (all the logic is in {@link SvgView}), this * "stubbed" ViewManager is used for all of them. */ -class RenderableViewManager extends ViewManager { +class RenderableViewManager extends ViewGroupManager> { /* package */ private static final String CLASS_GROUP = "RNSVGGroup"; /* package */ private static final String CLASS_PATH = "RNSVGPath"; @@ -38,48 +48,283 @@ class RenderableViewManager extends ViewManager { /* package */ private static final String CLASS_SYMBOL = "RNSVGSymbol"; /* package */ private static final String CLASS_LINEAR_GRADIENT = "RNSVGLinearGradient"; /* package */ private static final String CLASS_RADIAL_GRADIENT = "RNSVGRadialGradient"; + /* package */ private static final String CLASS_PATTERN = "RNSVGPattern"; + /* package */ private static final String CLASS_MASK = "RNSVGMask"; private final String mClassName; - static RenderableViewManager createGroupViewManager() { - return new RenderableViewManager(CLASS_GROUP); + static RenderableViewManager createGroupViewManager() { + return new RenderableViewManager<>(CLASS_GROUP); } - static RenderableViewManager createPathViewManager() { - return new RenderableViewManager(CLASS_PATH); + static RenderableViewManager createPathViewManager() { + return new RenderableViewManager(CLASS_PATH) { + + @ReactProp(name = "d") + public void setD(RenderableView node, String d) { + node.shadowNode.setD(d); + } + }; } - static RenderableViewManager createTextViewManager() { - return new RenderableViewManager(CLASS_TEXT); + static RenderableViewManager createTextViewManager() { + return new RenderableViewManager(CLASS_TEXT) { + + @ReactProp(name = "textLength") + public void setTextLength(RenderableView node, @Nullable String length) { + node.shadowNode.setTextLength(length); + } + + @ReactProp(name = "lengthAdjust") + public void setLengthAdjust(RenderableView node, @Nullable String adjustment) { + node.shadowNode.setLengthAdjust(adjustment); + } + + @ReactProp(name = "alignmentBaseline") + public void setMethod(RenderableView node, @Nullable String alignment) { + node.shadowNode.setMethod(alignment); + } + + @ReactProp(name = "baselineShift") + public void setBaselineShift(RenderableView node, @Nullable String baselineShift) { + node.shadowNode.setBaselineShift(baselineShift); + } + + @ReactProp(name = "verticalAlign") + public void setVerticalAlign(RenderableView node, @Nullable String verticalAlign) { + node.shadowNode.setVerticalAlign(verticalAlign); + } + + @ReactProp(name = "rotate") + public void setRotate(RenderableView node, @Nullable ReadableArray rotate) { + node.shadowNode.setRotate(rotate); + } + + @ReactProp(name = "deltaX") + public void setDeltaX(RenderableView node, @Nullable ReadableArray deltaX) { + node.shadowNode.setDeltaX(deltaX); + } + + @ReactProp(name = "deltaY") + public void setDeltaY(RenderableView node, @Nullable ReadableArray deltaY) { + node.shadowNode.setDeltaY(deltaY); + } + + @ReactProp(name = "positionX") + public void setPositionX(RenderableView node, @Nullable ReadableArray positionX) { + node.shadowNode.setPositionX(positionX); + } + + @ReactProp(name = "positionY") + public void setPositionY(RenderableView node, @Nullable ReadableArray positionY) { + node.shadowNode.setPositionY(positionY); + } + + @ReactProp(name = "font") + public void setFont(RenderableView node, @Nullable ReadableMap font) { + node.shadowNode.setFont(font); + } + }; } - static RenderableViewManager createTSpanViewManager() { - return new RenderableViewManager(CLASS_TSPAN); + static RenderableViewManager createTSpanViewManager() { + return new RenderableViewManager(CLASS_TSPAN) { + + @ReactProp(name = "content") + public void setContent(RenderableView node, @Nullable String content) { + node.shadowNode.setContent(content); + } + }; } - static RenderableViewManager createTextPathViewManager() { - return new RenderableViewManager(CLASS_TEXT_PATH); + static RenderableViewManager createTextPathViewManager() { + return new RenderableViewManager(CLASS_TEXT_PATH) { + + @ReactProp(name = "href") + public void setHref(RenderableView node, String href) { + node.shadowNode.setHref(href); + } + + @ReactProp(name = "startOffset") + public void setStartOffset(RenderableView node, @Nullable String startOffset) { + node.shadowNode.setStartOffset(startOffset); + } + + @ReactProp(name = "method") + public void setMethod(RenderableView node, @Nullable String method) { + node.shadowNode.setMethod(method); + } + + @ReactProp(name = "spacing") + public void setSpacing(RenderableView node, @Nullable String spacing) { + node.shadowNode.setSpacing(spacing); + } + + @ReactProp(name = "side") + public void setSide(RenderableView node, @Nullable String side) { + node.shadowNode.setSide(side); + } + + @ReactProp(name = "midLine") + public void setSharp(RenderableView node, @Nullable String midLine) { + node.shadowNode.setSharp(midLine); + } + }; } - static RenderableViewManager createImageViewManager() { - return new RenderableViewManager(CLASS_IMAGE); + static RenderableViewManager createImageViewManager() { + return new RenderableViewManager(CLASS_IMAGE) { + + @ReactProp(name = "x") + public void setX(RenderableView node, String x) { + node.shadowNode.setX(x); + } + + @ReactProp(name = "y") + public void setY(RenderableView node, String y) { + node.shadowNode.setY(y); + } + + @ReactProp(name = "imagewidth") + public void setWidth(RenderableView node, String width) { + node.shadowNode.setWidth(width); + } + + @ReactProp(name = "imageheight") + public void seHeight(RenderableView node, String height) { + node.shadowNode.seHeight(height); + } + + @ReactProp(name = "src") + public void setSrc(RenderableView node, @Nullable ReadableMap src) { + node.shadowNode.setSrc(src); + } + + + @ReactProp(name = "align") + public void setAlign(RenderableView node, String align) { + node.shadowNode.setAlign(align); + } + + @ReactProp(name = "meetOrSlice") + public void setMeetOrSlice(RenderableView node, int meetOrSlice) { + node.shadowNode.setMeetOrSlice(meetOrSlice); + } + + @ReactProp(name = "matrix") + public void setMatrix(RenderableView node, @Nullable ReadableArray matrixArray) { + node.shadowNode.setMatrix(matrixArray); + } + }; } - static RenderableViewManager createCircleViewManager() { - return new RenderableViewManager(CLASS_CIRCLE); + static RenderableViewManager createCircleViewManager() { + return new RenderableViewManager(CLASS_CIRCLE) { + + @ReactProp(name = "cx") + public void setCx(RenderableView node, String cx) { + node.shadowNode.setCx(cx); + } + + @ReactProp(name = "cy") + public void setCy(RenderableView node, String cy) { + node.shadowNode.setCy(cy); + } + + @ReactProp(name = "r") + public void setR(RenderableView node, String r) { + node.shadowNode.setR(r); + } + }; } - static RenderableViewManager createEllipseViewManager() { - return new RenderableViewManager(CLASS_ELLIPSE); + static RenderableViewManager createEllipseViewManager() { + return new RenderableViewManager(CLASS_ELLIPSE) { + + @ReactProp(name = "cx") + public void setCx(RenderableView node, String cx) { + node.shadowNode.setCx(cx); + } + + @ReactProp(name = "cy") + public void setCy(RenderableView node, String cy) { + node.shadowNode.setCy(cy); + } + + @ReactProp(name = "rx") + public void setRx(RenderableView node, String rx) { + node.shadowNode.setRx(rx); + } + + @ReactProp(name = "ry") + public void setRy(RenderableView node, String ry) { + node.shadowNode.setRy(ry); + } + }; } - static RenderableViewManager createLineViewManager() { - return new RenderableViewManager(CLASS_LINE); + static RenderableViewManager createLineViewManager() { + return new RenderableViewManager(CLASS_LINE) { + + @ReactProp(name = "x1") + public void setX1(RenderableView node, String x1) { + node.shadowNode.setX1(x1); + } + + @ReactProp(name = "y1") + public void setY1(RenderableView node, String y1) { + node.shadowNode.setY1(y1); + } + + @ReactProp(name = "x2") + public void setX2(RenderableView node, String x2) { + node.shadowNode.setX2(x2); + } + + @ReactProp(name = "y2") + public void setY2(RenderableView node, String y2) { + node.shadowNode.setY2(y2); + } + + }; } - static RenderableViewManager createRectViewManager() { - return new RenderableViewManager(CLASS_RECT); + static RenderableViewManager createRectViewManager() { + return new RenderableViewManager(CLASS_RECT) { + + @ReactProp(name = "x") + public void setX(RenderableView node, String x) { + node.shadowNode.setX(x); + } + + @ReactProp(name = "y") + public void setY(RenderableView node, String y) { + node.shadowNode.setY(y); + } + + @ReactProp(name = "rectwidth") + public void setWidth(RenderableView node, String width) { + node.shadowNode.setWidth(width); + } + + + @ReactProp(name = "rectheight") + public void setHeight(RenderableView node, String height) { + node.shadowNode.setHeight(height); + } + + + @ReactProp(name = "rx") + public void setRx(RenderableView node, String rx) { + node.shadowNode.setRx(rx); + } + + @ReactProp(name = "ry") + public void setRy(RenderableView node, String ry) { + node.shadowNode.setRy(ry); + } + }; } static RenderableViewManager createClipPathViewManager() { @@ -90,20 +335,259 @@ static RenderableViewManager createDefsViewManager() { return new RenderableViewManager(CLASS_DEFS); } - static RenderableViewManager createUseViewManager() { - return new RenderableViewManager(CLASS_USE); + static RenderableViewManager createUseViewManager() { + return new RenderableViewManager(CLASS_USE) { + + @ReactProp(name = "href") + public void setHref(RenderableView node, String href) { + node.shadowNode.setHref(href); + } + + @ReactProp(name = "usewidth") + public void setWidth(RenderableView node, String width) { + node.shadowNode.setWidth(width); + } + + @ReactProp(name = "useheight") + public void setHeight(RenderableView node, String height) { + node.shadowNode.setHeight(height); + } + }; + } + + static RenderableViewManager createSymbolManager() { + return new RenderableViewManager(CLASS_SYMBOL) { + + @ReactProp(name = "minX") + public void setMinX(RenderableView node, float minX) { + node.shadowNode.setMinX(minX); + } + + @ReactProp(name = "minY") + public void setMinY(RenderableView node, float minY) { + node.shadowNode.setMinY(minY); + } + + @ReactProp(name = "vbWidth") + public void setVbWidth(RenderableView node, float vbWidth) { + node.shadowNode.setVbWidth(vbWidth); + } + + @ReactProp(name = "vbHeight") + public void setVbHeight(RenderableView node, float vbHeight) { + node.shadowNode.setVbHeight(vbHeight); + } + + @ReactProp(name = "align") + public void setAlign(RenderableView node, String align) { + node.shadowNode.setAlign(align); + } + + @ReactProp(name = "meetOrSlice") + public void setMeetOrSlice(RenderableView node, int meetOrSlice) { + node.shadowNode.setMeetOrSlice(meetOrSlice); + } + }; + } + + static RenderableViewManager createPatternManager() { + return new RenderableViewManager(CLASS_PATTERN) { + + @ReactProp(name = "x") + public void setX(RenderableView node, String x) { + node.shadowNode.setX(x); + } + + @ReactProp(name = "y") + public void setY(RenderableView node, String y) { + node.shadowNode.setY(y); + } + + @ReactProp(name = "patternwidth") + public void setWidth(RenderableView node, String width) { + node.shadowNode.setWidth(width); + } + + @ReactProp(name = "patternheight") + public void setHeight(RenderableView node, String height) { + node.shadowNode.setHeight(height); + } + + @ReactProp(name = "patternUnits") + public void setPatternUnits(RenderableView node, int patternUnits) { + node.shadowNode.setPatternUnits(patternUnits); + } + + @ReactProp(name = "patternContentUnits") + public void setPatternContentUnits(RenderableView node, int patternContentUnits) { + node.shadowNode.setPatternContentUnits(patternContentUnits); + } + + @ReactProp(name = "patternTransform") + public void setPatternTransform(RenderableView node, @Nullable ReadableArray matrixArray) { + node.shadowNode.setPatternTransform(matrixArray); + } + + @ReactProp(name = "minX") + public void setMinX(RenderableView node, float minX) { + node.shadowNode.setMinX(minX); + } + + @ReactProp(name = "minY") + public void setMinY(RenderableView node, float minY) { + node.shadowNode.setMinY(minY); + } + + @ReactProp(name = "vbWidth") + public void setVbWidth(RenderableView node, float vbWidth) { + node.shadowNode.setVbWidth(vbWidth); + } + + @ReactProp(name = "vbHeight") + public void setVbHeight(RenderableView node, float vbHeight) { + node.shadowNode.setVbHeight(vbHeight); + } + + @ReactProp(name = "align") + public void setAlign(RenderableView node, String align) { + node.shadowNode.setAlign(align); + } + + @ReactProp(name = "meetOrSlice") + public void setMeetOrSlice(RenderableView node, int meetOrSlice) { + node.shadowNode.setMeetOrSlice(meetOrSlice); + } + }; } - static RenderableViewManager createSymbolManager() { - return new RenderableViewManager(CLASS_SYMBOL); + static RenderableViewManager createMaskManager() { + return new RenderableViewManager(CLASS_MASK) { + + @ReactProp(name = "x") + public void setX(RenderableView node, String x) { + node.shadowNode.setX(x); + } + + @ReactProp(name = "y") + public void setY(RenderableView node, String y) { + node.shadowNode.setY(y); + } + + @ReactProp(name = "maskwidth") + public void setWidth(RenderableView node, String width) { + node.shadowNode.setWidth(width); + } + + @ReactProp(name = "maskheight") + public void setHeight(RenderableView node, String height) { + node.shadowNode.setHeight(height); + } + + @ReactProp(name = "maskUnits") + public void setMaskUnits(RenderableView node, int maskUnits) { + node.shadowNode.setMaskUnits(maskUnits); + } + + @ReactProp(name = "maskContentUnits") + public void setMaskContentUnits(RenderableView node, int maskContentUnits) { + node.shadowNode.setMaskContentUnits(maskContentUnits); + } + + @ReactProp(name = "maskTransform") + public void setMaskTransform(RenderableView node, @Nullable ReadableArray matrixArray) { + node.shadowNode.setMaskTransform(matrixArray); + } + }; } - static RenderableViewManager createLinearGradientManager() { - return new RenderableViewManager(CLASS_LINEAR_GRADIENT); + static RenderableViewManager createLinearGradientManager() { + return new RenderableViewManager(CLASS_LINEAR_GRADIENT) { + + @ReactProp(name = "x1") + public void setX1(RenderableView node, String x1) { + node.shadowNode.setX1(x1); + } + + @ReactProp(name = "y1") + public void setY1(RenderableView node, String y1) { + node.shadowNode.setY1(y1); + } + + @ReactProp(name = "x2") + public void setX2(RenderableView node, String x2) { + node.shadowNode.setX2(x2); + } + + @ReactProp(name = "y2") + public void setY2(RenderableView node, String y2) { + node.shadowNode.setY2(y2); + } + + @ReactProp(name = "gradient") + public void setGradient(RenderableView node, ReadableArray gradient) { + node.shadowNode.setGradient(gradient); + } + + @ReactProp(name = "gradientUnits") + public void setGradientUnits(RenderableView node, int gradientUnits) { + node.shadowNode.setGradientUnits(gradientUnits); + } + + @ReactProp(name = "gradientTransform") + public void setGradientTransform(RenderableView node, @Nullable ReadableArray matrixArray) { + node.shadowNode.setGradientTransform(matrixArray); + } + }; } - static RenderableViewManager createRadialGradientManager() { - return new RenderableViewManager(CLASS_RADIAL_GRADIENT); + static RenderableViewManager createRadialGradientManager() { + return new RenderableViewManager(CLASS_RADIAL_GRADIENT) { + + @ReactProp(name = "fx") + public void setFx(RenderableView node, String fx) { + node.shadowNode.setFx(fx); + } + + @ReactProp(name = "fy") + public void setFy(RenderableView node, String fy) { + node.shadowNode.setFy(fy); + } + + @ReactProp(name = "rx") + public void setRx(RenderableView node, String rx) { + node.shadowNode.setRx(rx); + } + + @ReactProp(name = "ry") + public void setRy(RenderableView node, String ry) { + node.shadowNode.setRy(ry); + } + + @ReactProp(name = "cx") + public void setCx(RenderableView node, String cx) { + node.shadowNode.setCx(cx); + } + + @ReactProp(name = "cy") + public void setCy(RenderableView node, String cy) { + node.shadowNode.setCy(cy); + } + + @ReactProp(name = "gradient") + public void setGradient(RenderableView node, ReadableArray gradient) { + node.shadowNode.setGradient(gradient); + } + + @ReactProp(name = "gradientUnits") + public void setGradientUnits(RenderableView node, int gradientUnits) { + node.shadowNode.setGradientUnits(gradientUnits); + } + + @ReactProp(name = "gradientTransform") + public void setGradientTransform(RenderableView node, @Nullable ReadableArray matrixArray) { + node.shadowNode.setGradientTransform(matrixArray); + } + }; } private RenderableViewManager(String className) { @@ -150,13 +634,17 @@ public LayoutShadowNode createShadowNodeInstance() { return new LinearGradientShadowNode(); case CLASS_RADIAL_GRADIENT: return new RadialGradientShadowNode(); + case CLASS_PATTERN: + return new PatternShadowNode(); + case CLASS_MASK: + return new MaskShadowNode(); default: throw new IllegalStateException("Unexpected type " + mClassName); } } @Override - public Class getShadowNodeClass() { + public Class getShadowNodeClass() { switch (mClassName) { case CLASS_GROUP: return GroupShadowNode.class; @@ -190,22 +678,134 @@ public Class getShadowNodeClass() { return LinearGradientShadowNode.class; case CLASS_RADIAL_GRADIENT: return RadialGradientShadowNode.class; + case CLASS_PATTERN: + return PatternShadowNode.class; + case CLASS_MASK: + return MaskShadowNode.class; default: throw new IllegalStateException("Unexpected type " + mClassName); } } + @ReactProp(name = "mask") + public void setMask(RenderableView node, String mask) { + node.shadowNode.setMask(mask); + } + + @ReactProp(name = "clipPath") + public void setClipPath(RenderableView node, String mask) { + node.shadowNode.setClipPath(mask); + } + + @ReactProp(name = "clipRule") + public void setClipRule(RenderableView node, int clipRule) { + node.shadowNode.setClipRule(clipRule); + } + + @ReactProp(name = "fill") + public void setFill(RenderableView node, @Nullable Dynamic fill) { + node.shadowNode.setFill(fill); + } + + @ReactProp(name = "fillOpacity", defaultFloat = 1f) + public void setFillOpacity(RenderableView node, float fillOpacity) { + node.shadowNode.setFillOpacity(fillOpacity); + } + + @ReactProp(name = "fillRule", defaultInt = FILL_RULE_NONZERO) + public void setFillRule(RenderableView node, int fillRule) { + node.shadowNode.setFillRule(fillRule); + } + + + @ReactProp(name = "stroke") + public void setStroke(RenderableView node, @Nullable Dynamic strokeColors) { + node.shadowNode.setStroke(strokeColors); + } + + @ReactProp(name = "strokeOpacity", defaultFloat = 1f) + public void setStrokeOpacity(RenderableView node, float strokeOpacity) { + node.shadowNode.setStrokeOpacity(strokeOpacity); + } + + @ReactProp(name = "strokeDasharray") + public void setStrokeDasharray(RenderableView node, @Nullable ReadableArray strokeDasharray) { + node.shadowNode.setStrokeDasharray(strokeDasharray); + } + + @ReactProp(name = "strokeDashoffset") + public void setStrokeDashoffset(RenderableView node, float strokeDashoffset) { + node.shadowNode.setStrokeDashoffset(strokeDashoffset); + } + + @ReactProp(name = "strokeWidth") + public void setStrokeWidth(RenderableView node, String strokeWidth) { + node.shadowNode.setStrokeWidth(strokeWidth); + } + + @ReactProp(name = "strokeMiterlimit", defaultFloat = 4f) + public void setStrokeMiterlimit(RenderableView node, float strokeMiterlimit) { + node.shadowNode.setStrokeMiterlimit(strokeMiterlimit); + } + + @ReactProp(name = "strokeLinecap", defaultInt = CAP_ROUND) + public void setStrokeLinecap(RenderableView node, int strokeLinecap) { + node.shadowNode.setStrokeLinecap(strokeLinecap); + } + + @ReactProp(name = "strokeLinejoin", defaultInt = JOIN_ROUND) + public void setStrokeLinejoin(RenderableView node, int strokeLinejoin) { + node.shadowNode.setStrokeLinejoin(strokeLinejoin); + } + + @ReactProp(name = "propList") + public void setPropList(RenderableView node, @Nullable ReadableArray propList) { + node.shadowNode.setPropList(propList); + } + + /** + * Callback that will be triggered after all properties are updated in current update transaction + * (all @ReactProp handlers for properties updated in current transaction have been called). If + * you want to override this method you should call super.onAfterUpdateTransaction from it as + * the parent class of the ViewManager may rely on callback being executed. + */ + protected void onAfterUpdateTransaction(RenderableView node) { + super.onAfterUpdateTransaction(node); + VirtualNode shadow = node.shadowNode; + SvgViewShadowNode view = shadow.getSvgShadowNode(); + if (view == null) { + return; + } + SvgView root = SvgViewManager.getSvgViewByTag(view.getReactTag()); + if (root == null) { + return; + } + root.invalidate(); + } + @Override - protected View createViewInstance(ThemedReactContext reactContext) { - throw new IllegalStateException("SVG elements does not map into a native view"); + protected RenderableView createViewInstance(ThemedReactContext reactContext) { + return new RenderableView(reactContext); } @Override - public void updateExtraData(View root, Object extraData) { + public void updateExtraData(RenderableView root, Object extraData) { throw new IllegalStateException("SVG elements does not map into a native view"); } + private static final SparseArray mTagToShadowNode = new SparseArray<>(); + @Override - public void onDropViewInstance(View view) { + public void onDropViewInstance(RenderableView view) { + mTagToShadowNode.remove(view.getId()); + view.dropView(); + } + + static void setShadowNode(VirtualNode virtualNode) { + mTagToShadowNode.put(virtualNode.getReactTag(), virtualNode); + } + + static VirtualNode getShadowNodeByTag(int id) { + return mTagToShadowNode.get(id); } } diff --git a/android/src/main/java/com/horcrux/svg/SvgPackage.java b/android/src/main/java/com/horcrux/svg/SvgPackage.java index be0605aba..499a3770c 100644 --- a/android/src/main/java/com/horcrux/svg/SvgPackage.java +++ b/android/src/main/java/com/horcrux/svg/SvgPackage.java @@ -41,6 +41,8 @@ public List createViewManagers(ReactApplicationContext reactContext RenderableViewManager.createSymbolManager(), RenderableViewManager.createLinearGradientManager(), RenderableViewManager.createRadialGradientManager(), + RenderableViewManager.createPatternManager(), + RenderableViewManager.createMaskManager(), new SvgViewManager()); } diff --git a/android/src/main/java/com/horcrux/svg/SvgView.java b/android/src/main/java/com/horcrux/svg/SvgView.java index 1281294f3..0d2e42099 100644 --- a/android/src/main/java/com/horcrux/svg/SvgView.java +++ b/android/src/main/java/com/horcrux/svg/SvgView.java @@ -66,6 +66,12 @@ public SvgView(ReactContext reactContext) { mEventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); } + public void addView(View child, int index, LayoutParams params) { + if (!(child instanceof RenderableView)) { + super.addView(child, index, params); + } + } + @Override public void setId(int id) { super.setId(id); @@ -78,20 +84,22 @@ protected void onDetachedFromWindow() { SvgViewManager.dropSvgView(this); } - public void setBitmap(Bitmap bitmap) { + @Override + public void invalidate() { + super.invalidate(); if (mBitmap != null) { mBitmap.recycle(); } - mBitmap = bitmap; - invalidate(); + mBitmap = null; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); - if (mBitmap != null) { - canvas.drawBitmap(mBitmap, 0, 0, null); + if (mBitmap == null) { + mBitmap = getShadowNode().drawOutput(); } + canvas.drawBitmap(mBitmap, 0, 0, null); } private SvgViewShadowNode getShadowNode() { @@ -133,6 +141,8 @@ protected void onLayout(boolean changed, int l, int t, int r, int b) { child.layout(Math.round(x), Math.round(y), Math.round(nr), Math.round(nb)); break; } + } else { + child.layout(l, t, r , b); } } } diff --git a/android/src/main/java/com/horcrux/svg/SvgViewManager.java b/android/src/main/java/com/horcrux/svg/SvgViewManager.java index 6f388741c..cd60121d5 100644 --- a/android/src/main/java/com/horcrux/svg/SvgViewManager.java +++ b/android/src/main/java/com/horcrux/svg/SvgViewManager.java @@ -9,7 +9,6 @@ package com.horcrux.svg; -import android.graphics.Bitmap; import android.util.SparseArray; import com.facebook.react.uimanager.ThemedReactContext; @@ -90,7 +89,7 @@ protected SvgView createViewInstance(ThemedReactContext reactContext) { @Override public void updateExtraData(SvgView root, Object extraData) { - root.setBitmap((Bitmap) extraData); + root.invalidate(); } } diff --git a/android/src/main/java/com/horcrux/svg/SvgViewShadowNode.java b/android/src/main/java/com/horcrux/svg/SvgViewShadowNode.java index 21737e900..502099e3f 100644 --- a/android/src/main/java/com/horcrux/svg/SvgViewShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/SvgViewShadowNode.java @@ -22,13 +22,13 @@ import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.LayoutShadowNode; import com.facebook.react.uimanager.ReactShadowNode; +import com.facebook.react.uimanager.ReactShadowNodeImpl; import com.facebook.react.uimanager.UIViewOperationQueue; import com.facebook.react.uimanager.annotations.ReactProp; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; -import java.util.Stack; /** * Shadow node for RNSVG virtual tree root - RNSVGSvgView @@ -38,6 +38,7 @@ public class SvgViewShadowNode extends LayoutShadowNode { private final Map mDefinedClipPaths = new HashMap<>(); private final Map mDefinedTemplates = new HashMap<>(); + private final Map mDefinedMasks = new HashMap<>(); private final Map mDefinedBrushes = new HashMap<>(); private Canvas mCanvas; private final float mScale; @@ -52,58 +53,81 @@ public class SvgViewShadowNode extends LayoutShadowNode { private int mMeetOrSlice; private Matrix mInvViewBoxMatrix = new Matrix(); private boolean mInvertible = true; - + private boolean mRendered = false; public SvgViewShadowNode() { mScale = DisplayMetricsHolder.getScreenDisplayMetrics().density; } + private void releaseCachedPath() { + if (!mRendered) { + return; + } + mRendered = false; + traverseChildren(new VirtualNode.NodeRunnable() { + public void run(ReactShadowNode node) { + if (node instanceof VirtualNode) { + VirtualNode n = ((VirtualNode)node); + n.releaseCachedPath(); + } + } + }); + } + @ReactProp(name = "minX") public void setMinX(float minX) { mMinX = minX; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "minY") public void setMinY(float minY) { mMinY = minY; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "vbWidth") public void setVbWidth(float vbWidth) { mVbWidth = vbWidth; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "vbHeight") public void setVbHeight(float vbHeight) { mVbHeight = vbHeight; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "bbWidth") public void setVbWidth(String bbWidth) { mbbWidth = bbWidth; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "bbHeight") public void setVbHeight(String bbHeight) { mbbHeight = bbHeight; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "align") public void setAlign(String align) { mAlign = align; markUpdated(); + releaseCachedPath(); } @ReactProp(name = "meetOrSlice") public void setMeetOrSlice(int meetOrSlice) { mMeetOrSlice = meetOrSlice; markUpdated(); + releaseCachedPath(); } @Override @@ -119,7 +143,7 @@ public boolean isVirtualAnchor() { @Override public void onCollectExtraUpdates(UIViewOperationQueue uiUpdater) { super.onCollectExtraUpdates(uiUpdater); - uiUpdater.enqueueUpdateExtraData(getReactTag(), drawOutput()); + uiUpdater.enqueueUpdateExtraData(getReactTag(), null); } @Override @@ -128,19 +152,25 @@ public void setReactTag(int reactTag) { SvgViewManager.setShadowNode(this); } - private Object drawOutput() { - int layoutWidth = (int) getLayoutWidth(); - int layoutHeight = (int) getLayoutHeight(); - if(layoutHeight != 0 && layoutWidth != 0) { - Bitmap bitmap = Bitmap.createBitmap( - layoutWidth, - layoutHeight, - Bitmap.Config.ARGB_8888); - - drawChildren(new Canvas(bitmap)); - return bitmap; + Bitmap drawOutput() { + mRendered = true; + float width = getLayoutWidth(); + float height = getLayoutHeight(); + boolean early = Float.isNaN(width) || Float.isNaN(height) || width * height == 0 || (Math.log10(width) + Math.log10(height) > 42); + if (early) { + ReactShadowNodeImpl parent = getParent(); + float parentWidth = parent == null ? 0 : parent.getLayoutWidth(); + float parentHeight = parent == null ? 0 : parent.getLayoutHeight(); + width = (float) PropHelper.fromRelative(mbbWidth, parentWidth, 0, mScale, 12); + height = (float) PropHelper.fromRelative(mbbHeight, parentHeight, 0, mScale, 12); } - return null; + Bitmap bitmap = Bitmap.createBitmap( + (int) width, + (int) height, + Bitmap.Config.ARGB_8888); + + drawChildren(new Canvas(bitmap)); + return bitmap; } Rect getCanvasBounds() { @@ -151,15 +181,12 @@ void drawChildren(final Canvas canvas) { mCanvas = canvas; if (mAlign != null) { RectF vbRect = getViewBox(); - float width; - float height; + float width = canvas.getWidth(); + float height = canvas.getHeight(); boolean nested = getNativeParent() instanceof SvgViewShadowNode; if (nested) { - width = Float.parseFloat(mbbWidth) * mScale; - height = Float.parseFloat(mbbHeight) * mScale; - } else { - width = getLayoutWidth(); - height = getLayoutHeight(); + width = (float) PropHelper.fromRelative(mbbWidth, width, 0f, mScale, 12); + height = (float) PropHelper.fromRelative(mbbHeight, height, 0f, mScale, 12); } RectF eRect = new RectF(0,0, width, height); if (nested) { @@ -190,7 +217,7 @@ public void run(ReactShadowNode lNode) { if (lNode instanceof VirtualNode) { VirtualNode node = (VirtualNode)lNode; int count = node.saveAndSetupCanvas(canvas); - node.draw(canvas, paint, 1f); + node.render(canvas, paint, 1f); node.restoreCanvas(canvas, count); node.markUpdateSeen(); @@ -239,11 +266,12 @@ int hitTest(Point point) { int count = getChildCount(); int viewTag = -1; for (int i = count - 1; i >= 0; i--) { - if (!(getChildAt(i) instanceof VirtualNode)) { + ReactShadowNodeImpl child = getChildAt(i); + if (!(child instanceof VirtualNode)) { continue; } - viewTag = ((VirtualNode) getChildAt(i)).hitTest(transformed); + viewTag = ((VirtualNode) child).hitTest(transformed); if (viewTag != -1) { break; } @@ -276,6 +304,14 @@ Brush getDefinedBrush(String brushRef) { return mDefinedBrushes.get(brushRef); } + void defineMask(VirtualNode mask, String maskRef) { + mDefinedMasks.put(maskRef, mask); + } + + VirtualNode getDefinedMask(String maskRef) { + return mDefinedMasks.get(maskRef); + } + void traverseChildren(VirtualNode.NodeRunnable runner) { for (int i = 0; i < getChildCount(); i++) { ReactShadowNode child = getChildAt(i); diff --git a/android/src/main/java/com/horcrux/svg/TSpanShadowNode.java b/android/src/main/java/com/horcrux/svg/TSpanShadowNode.java index 01f74352b..b89381dd2 100644 --- a/android/src/main/java/com/horcrux/svg/TSpanShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/TSpanShadowNode.java @@ -17,7 +17,6 @@ import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.Rect; -import android.graphics.RectF; import android.graphics.Typeface; import android.os.Build; @@ -66,6 +65,7 @@ public void draw(Canvas canvas, Paint paint, float opacity) { @Override protected void releaseCachedPath() { mCache = null; + mPath = null; } @Override diff --git a/android/src/main/java/com/horcrux/svg/TextShadowNode.java b/android/src/main/java/com/horcrux/svg/TextShadowNode.java index 9b4225cfe..f3ab4df39 100644 --- a/android/src/main/java/com/horcrux/svg/TextShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/TextShadowNode.java @@ -12,6 +12,7 @@ import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; +import android.graphics.Region; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; @@ -35,8 +36,14 @@ class TextShadowNode extends GroupShadowNode { private @Nullable ReadableArray mDeltaX; private @Nullable ReadableArray mDeltaY; + @Override + public void markUpdated() { + super.markUpdated(); + releaseCachedPath(); + } + @ReactProp(name = "textLength") - public void setmTextLength(@Nullable String length) { + public void setTextLength(@Nullable String length) { mTextLength = length; markUpdated(); } @@ -124,7 +131,6 @@ public void draw(Canvas canvas, Paint paint, float opacity) { clip(canvas, paint); getGroupPath(canvas, paint); drawGroup(canvas, paint, opacity); - releaseCachedPath(); } } @@ -132,10 +138,14 @@ public void draw(Canvas canvas, Paint paint, float opacity) { protected Path getPath(Canvas canvas, Paint paint) { setupGlyphContext(canvas); Path groupPath = getGroupPath(canvas, paint); - releaseCachedPath(); return groupPath; } + @Override + protected Path getPath(Canvas canvas, Paint paint, Region.Op op) { + return getPath(canvas, paint); + } + AlignmentBaseline getAlignmentBaseline() { if (mAlignmentBaseline == null) { ReactShadowNode parent = this.getParent(); @@ -175,16 +185,6 @@ String getBaselineShift() { return mBaselineShift; } - void releaseCachedPath() { - traverseChildren(new NodeRunnable() { - public void run(ReactShadowNode node) { - if (node instanceof TextShadowNode) { - ((TextShadowNode)node).releaseCachedPath(); - } - } - }); - } - Path getGroupPath(Canvas canvas, Paint paint) { pushGlyphContext(); Path groupPath = super.getPath(canvas, paint); diff --git a/android/src/main/java/com/horcrux/svg/UseShadowNode.java b/android/src/main/java/com/horcrux/svg/UseShadowNode.java index 8363f511d..1b0aa5d15 100644 --- a/android/src/main/java/com/horcrux/svg/UseShadowNode.java +++ b/android/src/main/java/com/horcrux/svg/UseShadowNode.java @@ -32,13 +32,13 @@ public void setHref(String href) { markUpdated(); } - @ReactProp(name = "width") + @ReactProp(name = "usewidth") public void setWidth(String width) { mWidth = width; markUpdated(); } - @ReactProp(name = "height") + @ReactProp(name = "useheight") public void setHeight(String height) { mHeight = height; markUpdated(); diff --git a/android/src/main/java/com/horcrux/svg/VirtualNode.java b/android/src/main/java/com/horcrux/svg/VirtualNode.java index 0f1244e2d..b585efcab 100644 --- a/android/src/main/java/com/horcrux/svg/VirtualNode.java +++ b/android/src/main/java/com/horcrux/svg/VirtualNode.java @@ -41,6 +41,12 @@ abstract class VirtualNode extends LayoutShadowNode { static final float MIN_OPACITY_FOR_DRAW = 0.01f; + @Override + public void setReactTag(int reactTag) { + super.setReactTag(reactTag); + RenderableViewManager.setShadowNode(this); + } + private static final float[] sRawMatrix = new float[]{ 1, 0, 0, 0, 1, 0, @@ -50,10 +56,11 @@ abstract class VirtualNode extends LayoutShadowNode { Matrix mMatrix = new Matrix(); Matrix mInvMatrix = new Matrix(); boolean mInvertible = true; - RectF mClientRect; + private RectF mClientRect; private int mClipRule; private @Nullable String mClipPath; + @Nullable String mMask; private static final int CLIP_RULE_EVENODD = 0; private static final int CLIP_RULE_NONZERO = 1; @@ -76,23 +83,26 @@ abstract class VirtualNode extends LayoutShadowNode { Path mClipRegionPath; VirtualNode() { - setIsLayoutOnly(true); mScale = DisplayMetricsHolder.getScreenDisplayMetrics().density; } @Override public boolean isVirtual() { - return true; + return false; } @Override public boolean isVirtualAnchor() { - return true; + return false; } @Override public void markUpdated() { super.markUpdated(); + clearPath(); + } + + private void clearPath() { canvasHeight = -1; canvasWidth = -1; mRegion = null; @@ -100,6 +110,17 @@ public void markUpdated() { mBox = null; } + void releaseCachedPath() { + clearPath(); + traverseChildren(new NodeRunnable() { + public void run(ReactShadowNode node) { + if (node instanceof VirtualNode) { + ((VirtualNode)node).releaseCachedPath(); + } + } + }); + } + @Nullable GroupShadowNode getTextRoot() { VirtualNode node = this; @@ -148,6 +169,9 @@ private double getFontSizeFromContext() { } public abstract void draw(Canvas canvas, Paint paint, float opacity); + public void render(Canvas canvas, Paint paint, float opacity) { + draw(canvas, paint, opacity); + } /** * Sets up the transform matrix on the canvas before an element is drawn. @@ -181,6 +205,12 @@ public void setName(String name) { } + @ReactProp(name = "mask") + public void setMask(String mask) { + mMask = mask; + markUpdated(); + } + @ReactProp(name = "clipPath") public void setClipPath(String clipPath) { mCachedClipPath = null; @@ -189,7 +219,7 @@ public void setClipPath(String clipPath) { } @ReactProp(name = "clipRule", defaultInt = CLIP_RULE_NONZERO) - public void clipRule(int clipRule) { + public void setClipRule(int clipRule) { mClipRule = clipRule; markUpdated(); } @@ -234,10 +264,10 @@ public void setResponsible(boolean responsible) { @Nullable Path getClipPath(Canvas canvas, Paint paint) { if (mClipPath != null) { - VirtualNode node = getSvgShadowNode().getDefinedClipPath(mClipPath); + ClipPathShadowNode mClipNode = (ClipPathShadowNode) getSvgShadowNode().getDefinedClipPath(mClipPath); - if (node != null) { - Path clipPath = node.getPath(canvas, paint); + if (mClipNode != null) { + Path clipPath = mClipNode.getPath(canvas, paint, Region.Op.UNION); switch (mClipRule) { case CLIP_RULE_EVENODD: clipPath.setFillType(Path.FillType.EVEN_ODD); @@ -260,7 +290,7 @@ void clip(Canvas canvas, Paint paint) { Path clip = getClipPath(canvas, paint); if (clip != null) { - canvas.clipPath(clip, Region.Op.REPLACE); + canvas.clipPath(clip); } } diff --git a/elements/Image.js b/elements/Image.js index a8eb88e1a..88a455173 100644 --- a/elements/Image.js +++ b/elements/Image.js @@ -49,8 +49,8 @@ export default class extends Shape { {...extractProps({ ...props, x: null, y: null }, this)} x={props.x.toString()} y={props.y.toString()} - width={props.width.toString()} - height={props.height.toString()} + imagewidth={props.width.toString()} + imageheight={props.height.toString()} meetOrSlice={meetOrSlice} align={align} src={Image.resolveAssetSource(props.href)} diff --git a/elements/Mask.js b/elements/Mask.js new file mode 100644 index 000000000..30ae4a43a --- /dev/null +++ b/elements/Mask.js @@ -0,0 +1,71 @@ +import React, { Component } from "react"; +import PropTypes from 'prop-types'; +import { requireNativeComponent } from "react-native"; +import { numberProp } from '../lib/props'; +import PATTERN_UNITS from '../lib/PATTERN_UNITS'; +import { MaskAttributes } from '../lib/attributes'; +import extractTransform from '../lib/extract/extractTransform'; + +export default class extends Component { + static displayName = 'Mask'; + static propTypes = { + id: PropTypes.string.isRequired, + x: numberProp, + y: numberProp, + width: numberProp, + height: numberProp, + maskTransform: PropTypes.string, + maskUnits: PropTypes.oneOf(['userSpaceOnUse', 'objectBoundingBox']), + maskContentUnits: PropTypes.oneOf([ + 'userSpaceOnUse', + 'objectBoundingBox', + ]), + }; + + render() { + const { props } = this; + const { + maskTransform, + transform, + id, + x, + y, + width, + height, + maskUnits, + maskContentUnits, + children, + viewBox, + preserveAspectRatio, + } = props; + + let extractedTransform; + if (maskTransform) { + extractedTransform = extractTransform(maskTransform); + } else if (transform) { + extractedTransform = extractTransform(transform); + } else { + extractedTransform = extractTransform(props); + } + + return ( + + {children} + + ); + } +} + +const RNSVGMask = requireNativeComponent('RNSVGMask', null, { + nativeOnly: MaskAttributes, +}); diff --git a/elements/Pattern.js b/elements/Pattern.js index 1b9c8d1e4..a3ff97bce 100644 --- a/elements/Pattern.js +++ b/elements/Pattern.js @@ -1,23 +1,75 @@ -import { Component } from "react"; -import PropTypes from "prop-types"; -import { numberProp } from "../lib/props"; +import React, { Component } from "react"; +import PropTypes from 'prop-types'; +import { requireNativeComponent } from "react-native"; +import { numberProp } from '../lib/props'; +import PATTERN_UNITS from '../lib/PATTERN_UNITS'; +import { PatternAttributes } from '../lib/attributes'; +import extractTransform from '../lib/extract/extractTransform'; +import extractViewBox from "react-native-svg/lib/extract/extractViewBox"; export default class extends Component { - static displayName = "Pattern"; + static displayName = 'Pattern'; static propTypes = { - x1: numberProp, - x2: numberProp, - y1: numberProp, - y2: numberProp, + id: PropTypes.string.isRequired, + x: numberProp, + y: numberProp, + width: numberProp, + height: numberProp, patternTransform: PropTypes.string, - patternUnits: PropTypes.oneOf(["userSpaceOnUse", "objectBoundingBox"]), + patternUnits: PropTypes.oneOf(['userSpaceOnUse', 'objectBoundingBox']), patternContentUnits: PropTypes.oneOf([ - "userSpaceOnUse", - "objectBoundingBox" - ]) + 'userSpaceOnUse', + 'objectBoundingBox', + ]), + viewBox: PropTypes.string, + preserveAspectRatio: PropTypes.string }; render() { - return null; + const { props } = this; + const { + patternTransform, + transform, + id, + x, + y, + width, + height, + patternUnits, + patternContentUnits, + children, + viewBox, + preserveAspectRatio, + } = props; + + let extractedTransform; + if (patternTransform) { + extractedTransform = extractTransform(patternTransform); + } else if (transform) { + extractedTransform = extractTransform(transform); + } else { + extractedTransform = extractTransform(props); + } + + return ( + + {children} + + ); } } + +const RNSVGPattern = requireNativeComponent('RNSVGPattern', null, { + nativeOnly: PatternAttributes, +}); diff --git a/elements/Rect.js b/elements/Rect.js index fe9b8e19c..3d92fc765 100644 --- a/elements/Rect.js +++ b/elements/Rect.js @@ -50,8 +50,8 @@ export default class extends Shape { )} x={props.x.toString()} y={props.y.toString()} - width={props.width.toString()} - height={props.height.toString()} + rectwidth={props.width.toString()} + rectheight={props.height.toString()} rx={props.rx.toString()} ry={props.ry.toString()} /> diff --git a/elements/Use.js b/elements/Use.js index 88c176399..694a2fa18 100644 --- a/elements/Use.js +++ b/elements/Use.js @@ -52,8 +52,8 @@ export default class extends Shape { }} {...extractProps(props, this)} href={href} - width={width !== undefined ? width.toString() : ""} - height={height !== undefined ? height.toString() : ""} + usewidth={width !== undefined ? width.toString() : ""} + useheight={height !== undefined ? height.toString() : ""} > {children} diff --git a/index.js b/index.js index ba0e68378..7a2fc66b5 100644 --- a/index.js +++ b/index.js @@ -18,6 +18,8 @@ import LinearGradient from "./elements/LinearGradient"; import RadialGradient from "./elements/RadialGradient"; import Stop from "./elements/Stop"; import ClipPath from "./elements/ClipPath"; +import Pattern from "./elements/Pattern"; +import Mask from "./elements/Mask"; export { Svg, @@ -39,7 +41,9 @@ export { LinearGradient, RadialGradient, Stop, - ClipPath + ClipPath, + Pattern, + Mask, }; //noinspection JSUnusedGlobalSymbols diff --git a/ios/Brushes/RNSVGBrush.h b/ios/Brushes/RNSVGBrush.h index 7ffe6c892..28269eb7e 100644 --- a/ios/Brushes/RNSVGBrush.h +++ b/ios/Brushes/RNSVGBrush.h @@ -35,6 +35,6 @@ * be clipped. * @abstract */ -- (void)paint:(CGContextRef)context opacity:(CGFloat)opacity painter:(RNSVGPainter *)painter; +- (void)paint:(CGContextRef)context opacity:(CGFloat)opacity painter:(RNSVGPainter *)painter bounds:(CGRect)bounds; @end diff --git a/ios/Brushes/RNSVGPainter.h b/ios/Brushes/RNSVGPainter.h index 51347e9e0..00c680efe 100644 --- a/ios/Brushes/RNSVGPainter.h +++ b/ios/Brushes/RNSVGPainter.h @@ -10,14 +10,21 @@ #import "RNSVGBrushType.h" #import "RNSVGUnits.h" +@class RNSVGPattern; + @interface RNSVGPainter : NSObject +@property (nonatomic, assign) RNSVGPattern* pattern; +@property (nonatomic, assign) CGRect paintBounds; + - (instancetype)initWithPointsArray:(NSArray *)pointsArray NS_DESIGNATED_INITIALIZER; -- (void)paint:(CGContextRef)context; +- (void)paint:(CGContextRef)context bounds:(CGRect)bounds; - (void)setUnits:(RNSVGUnits)unit; +- (void)setContentUnits:(RNSVGUnits)unit; + - (void)setUserSpaceBoundingBox:(CGRect)userSpaceBoundingBox; - (void)setTransform:(CGAffineTransform)transform; diff --git a/ios/Brushes/RNSVGPainter.m b/ios/Brushes/RNSVGPainter.m index 1ba218803..b8973e9ec 100644 --- a/ios/Brushes/RNSVGPainter.m +++ b/ios/Brushes/RNSVGPainter.m @@ -7,7 +7,9 @@ */ #import "RNSVGPainter.h" +#import "RNSVGPattern.h" #import "RNSVGPercentageConverter.h" +#import "RNSVGViewBox.h" @implementation RNSVGPainter { @@ -15,6 +17,7 @@ @implementation RNSVGPainter NSArray *_colors; RNSVGBrushType _type; BOOL _useObjectBoundingBox; + BOOL _useContentObjectBoundingBox; CGAffineTransform _transform; CGRect _userSpaceBoundingBox; } @@ -34,6 +37,11 @@ - (void)setUnits:(RNSVGUnits)unit _useObjectBoundingBox = unit == kRNSVGUnitsObjectBoundingBox; } +- (void)setContentUnits:(RNSVGUnits)unit +{ + _useContentObjectBoundingBox = unit == kRNSVGUnitsObjectBoundingBox; +} + - (void)setUserSpaceBoundingBox:(CGRect)userSpaceBoundingBox { _userSpaceBoundingBox = userSpaceBoundingBox; @@ -44,6 +52,17 @@ - (void)setTransform:(CGAffineTransform)transform _transform = transform; } +- (void)setPattern:(RNSVGPattern *)pattern +{ + if (_type != kRNSVGUndefinedType) { + // todo: throw error + return; + } + + _type = kRNSVGPattern; + _pattern = pattern; +} + - (void)setLinearGradientColors:(NSArray *)colors { if (_type != kRNSVGUndefinedType) { @@ -66,20 +85,20 @@ - (void)setRadialGradientColors:(NSArray *)colors _colors = colors; } -- (void)paint:(CGContextRef)context +- (void)paint:(CGContextRef)context bounds:(CGRect)bounds { if (_type == kRNSVGLinearGradient) { - [self paintLinearGradient:context]; + [self paintLinearGradient:context bounds:(CGRect)bounds]; } else if (_type == kRNSVGRadialGradient) { - [self paintRidialGradient:context]; + [self paintRidialGradient:context bounds:(CGRect)bounds]; } else if (_type == kRNSVGPattern) { - // todo: + [self paintPattern:context bounds:(CGRect)bounds]; } } -- (CGRect)getPaintRect:(CGContextRef)context +- (CGRect)getPaintRect:(CGContextRef)context bounds:(CGRect)bounds { - CGRect rect = _useObjectBoundingBox ? CGContextGetClipBoundingBox(context) : _userSpaceBoundingBox; + CGRect rect = _useObjectBoundingBox ? bounds : _userSpaceBoundingBox; float height = CGRectGetHeight(rect); float width = CGRectGetWidth(rect); float x = 0.0; @@ -93,13 +112,74 @@ - (CGRect)getPaintRect:(CGContextRef)context return CGRectMake(x, y, width, height); } -- (void)paintLinearGradient:(CGContextRef)context +void PatternFunction(void* info, CGContextRef context) +{ + RNSVGPainter *_painter = (__bridge RNSVGPainter *)info; + RNSVGPattern *_pattern = [_painter pattern]; + CGRect rect = _painter.paintBounds; + + CGAffineTransform _viewBoxTransform = [RNSVGViewBox getTransform:CGRectMake(_pattern.minX, _pattern.minY, _pattern.vbWidth, _pattern.vbHeight) + eRect:rect + align:_pattern.align + meetOrSlice:_pattern.meetOrSlice]; + CGContextConcatCTM(context, _viewBoxTransform); + + [_pattern renderTo:context rect:rect]; +} + +- (void)paintPattern:(CGContextRef)context bounds:(CGRect)bounds +{ + CGRect rect = [self getPaintRect:context bounds:bounds]; + float height = CGRectGetHeight(rect); + float width = CGRectGetWidth(rect); + float offsetX = CGRectGetMinX(rect); + float offsetY = CGRectGetMinY(rect); + + CGFloat x = [RNSVGPercentageConverter stringToFloat:(NSString *)[_points objectAtIndex:0] + relative:width + offset:offsetX]; + CGFloat y = [RNSVGPercentageConverter stringToFloat:(NSString *)[_points objectAtIndex:1] + relative:height + offset:offsetY]; + CGFloat w = [RNSVGPercentageConverter stringToFloat:(NSString *)[_points objectAtIndex:2] + relative:width + offset:offsetX]; + CGFloat h = [RNSVGPercentageConverter stringToFloat:(NSString *)[_points objectAtIndex:3] + relative:height + offset:offsetY]; + + CGAffineTransform viewbox = [self.pattern.svgView getViewBoxTransform]; + CGRect newBounds = CGRectApplyAffineTransform(CGRectMake(x, y, w, h), viewbox); + CGSize size = newBounds.size; + self.paintBounds = newBounds; + + const CGPatternCallbacks callbacks = { 0, &PatternFunction, NULL }; + CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); + CGContextSetFillColorSpace(context, patternSpace); + CGColorSpaceRelease(patternSpace); + + CGPatternRef pattern = CGPatternCreate((__bridge void * _Nullable)(self), + newBounds, + CGAffineTransformIdentity, + size.width, + size.height, + kCGPatternTilingConstantSpacing, + true, + &callbacks); + CGFloat alpha = 1.0; + CGContextSetFillPattern(context, pattern, &alpha); + CGPatternRelease(pattern); + + CGContextFillRect(context, bounds); +} + +- (void)paintLinearGradient:(CGContextRef)context bounds:(CGRect)bounds { CGGradientRef gradient = CGGradientRetain([RCTConvert RNSVGCGGradient:_colors offset:0]); CGGradientDrawingOptions extendOptions = kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation; - CGRect rect = [self getPaintRect:context]; + CGRect rect = [self getPaintRect:context bounds:bounds]; float height = CGRectGetHeight(rect); float width = CGRectGetWidth(rect); float offsetX = CGRectGetMinX(rect); @@ -124,12 +204,12 @@ - (void)paintLinearGradient:(CGContextRef)context CGGradientRelease(gradient); } -- (void)paintRidialGradient:(CGContextRef)context +- (void)paintRidialGradient:(CGContextRef)context bounds:(CGRect)bounds { CGGradientRef gradient = CGGradientRetain([RCTConvert RNSVGCGGradient:_colors offset:0]); CGGradientDrawingOptions extendOptions = kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation; - CGRect rect = [self getPaintRect:context]; + CGRect rect = [self getPaintRect:context bounds:bounds]; float height = CGRectGetHeight(rect); float width = CGRectGetWidth(rect); float offsetX = CGRectGetMinX(rect); diff --git a/ios/Brushes/RNSVGPainterBrush.m b/ios/Brushes/RNSVGPainterBrush.m index 8b1b5d502..08d061eee 100644 --- a/ios/Brushes/RNSVGPainterBrush.m +++ b/ios/Brushes/RNSVGPainterBrush.m @@ -21,22 +21,22 @@ - (instancetype)initWithArray:(NSArray *)array self.class, NSStringFromSelector(_cmd), array); return nil; } - + self.brushRef = [array objectAtIndex:1]; } return self; } -- (void)paint:(CGContextRef)context opacity:(CGFloat)opacity painter:(RNSVGPainter *)painter +- (void)paint:(CGContextRef)context opacity:(CGFloat)opacity painter:(RNSVGPainter *)painter bounds:(CGRect)bounds { BOOL transparency = opacity < 1; if (transparency) { CGContextSetAlpha(context, opacity); CGContextBeginTransparencyLayer(context, NULL); } - - [painter paint:context]; - + + [painter paint:context bounds:(CGRect)bounds]; + if (transparency) { CGContextEndTransparencyLayer(context); } diff --git a/ios/Brushes/RNSVGPattern.m b/ios/Brushes/RNSVGPattern.m deleted file mode 100644 index 02983742e..000000000 --- a/ios/Brushes/RNSVGPattern.m +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2015-present, Horcrux. - * All rights reserved. - * - * This source code is licensed under the MIT-style license found in the - * LICENSE file in the root directory of this source tree. - */ - -#import "RNSVGPattern.h" - -#import "RCTConvert+RNSVG.h" -#import - -@implementation RNSVGPattern -{ - CGImageRef _image; - CGRect _rect; -} - -- (instancetype)initWithArray:(NSArray *)array -{ - if ((self = [super initWithArray:array])) { - if (array.count < 6) { - RCTLogError(@"-[%@ %@] expects 6 elements, received %@", - self.class, NSStringFromSelector(_cmd), array); - return nil; - } - _image = CGImageRetain([RCTConvert CGImage:array[1]]); - _rect = [RCTConvert RNSVGCGRect:array offset:2]; - } - return self; -} - -- (void)dealloc -{ - CGImageRelease(_image); -} - -// Note: This could use applyFillColor with a pattern. This could be more efficient but -// to do that, we need to calculate our own user space CTM. - -- (void)paint:(CGContextRef)context opacity:(CGFloat)opacity brushConverter:(RNSVGPainter *)brushConverter; -{ - CGContextDrawTiledImage(context, _rect, _image); -} - - - -@end diff --git a/ios/Elements/RNSVGClipPath.h b/ios/Elements/RNSVGClipPath.h index bed8b4a2a..27697e2a0 100644 --- a/ios/Elements/RNSVGClipPath.h +++ b/ios/Elements/RNSVGClipPath.h @@ -14,4 +14,6 @@ @interface RNSVGClipPath : RNSVGGroup +- (BOOL)isSimpleClipPath; + @end diff --git a/ios/Elements/RNSVGClipPath.m b/ios/Elements/RNSVGClipPath.m index 3ea72d6fe..3228920cd 100644 --- a/ios/Elements/RNSVGClipPath.m +++ b/ios/Elements/RNSVGClipPath.m @@ -10,15 +10,22 @@ @implementation RNSVGClipPath -- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event -{ - return nil; -} - - (void)parseReference { [self.svgView defineClipPath:self clipPathName:self.name]; } +- (BOOL)isSimpleClipPath +{ + NSArray *children = self.subviews; + if (children.count == 1) { + UIView* child = children[0]; + if ([child class] != [RNSVGGroup class]) { + return true; + } + } + return false; +} + @end diff --git a/ios/Elements/RNSVGGroup.m b/ios/Elements/RNSVGGroup.m index 5c78d177c..1871994c2 100644 --- a/ios/Elements/RNSVGGroup.m +++ b/ios/Elements/RNSVGGroup.m @@ -7,6 +7,7 @@ */ #import "RNSVGGroup.h" +#import "RNSVGClipPath.h" @implementation RNSVGGroup { @@ -33,7 +34,7 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect - (void)renderGroupTo:(CGContextRef)context rect:(CGRect)rect { [self pushGlyphContext]; - + __block CGRect groupRect = CGRectNull; [self traverseSubviews:^(UIView *node) { @@ -48,7 +49,7 @@ - (void)renderGroupTo:(CGContextRef)context rect:(CGRect)rect } [svgNode renderTo:context rect:rect]; - + CGRect nodeRect = svgNode.clientRect; if (!CGRectIsEmpty(nodeRect)) { groupRect = CGRectUnion(groupRect, nodeRect); @@ -59,7 +60,9 @@ - (void)renderGroupTo:(CGContextRef)context rect:(CGRect)rect } } else if ([node isKindOfClass:[RNSVGSvgView class]]) { RNSVGSvgView* svgView = (RNSVGSvgView*)node; - CGRect rect = CGRectMake(0, 0, [svgView.bbWidth floatValue], [svgView.bbHeight floatValue]); + CGFloat width = [self relativeOnWidth:svgView.bbWidth]; + CGFloat height = [self relativeOnHeight:svgView.bbHeight]; + CGRect rect = CGRectMake(0, 0, width, height); CGContextClipToRect(context, rect); [svgView drawToContext:context withRect:(CGRect)rect]; } else { @@ -122,12 +125,22 @@ - (CGPathRef)getPath:(CGContextRef)context - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { CGPoint transformed = CGPointApplyAffineTransform(point, self.invmatrix); - - CGPathRef clip = [self getClipPath]; - if (clip && !CGPathContainsPoint(clip, nil, transformed, self.clipRule == kRNSVGCGFCRuleEvenodd)) { - return nil; + + if (self.clipPath) { + RNSVGClipPath *clipNode = (RNSVGClipPath*)[self.svgView getDefinedClipPath:self.clipPath]; + if ([clipNode isSimpleClipPath]) { + CGPathRef clipPath = [self getClipPath]; + if (clipPath && !CGPathContainsPoint(clipPath, nil, transformed, self.clipRule == kRNSVGCGFCRuleEvenodd)) { + return nil; + } + } else { + RNSVGRenderable *clipGroup = (RNSVGRenderable*)clipNode; + if (![clipGroup hitTest:transformed withEvent:event]) { + return nil; + } + } } - + if (!event) { NSPredicate *const anyActive = [NSPredicate predicateWithFormat:@"active == TRUE"]; NSArray *const filtered = [self.subviews filteredArrayUsingPredicate:anyActive]; @@ -154,12 +167,12 @@ - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event return (node.responsible || (node != hitChild)) ? hitChild : self; } } - + UIView *hitSelf = [super hitTest:transformed withEvent:event]; if (hitSelf) { return hitSelf; } - + return nil; } diff --git a/ios/Elements/RNSVGImage.h b/ios/Elements/RNSVGImage.h index 303bdd29f..2691087c3 100644 --- a/ios/Elements/RNSVGImage.h +++ b/ios/Elements/RNSVGImage.h @@ -18,8 +18,8 @@ @property (nonatomic, assign) id src; @property (nonatomic, strong) NSString* x; @property (nonatomic, strong) NSString* y; -@property (nonatomic, strong) NSString* width; -@property (nonatomic, strong) NSString* height; +@property (nonatomic, strong) NSString* imagewidth; +@property (nonatomic, strong) NSString* imageheight; @property (nonatomic, strong) NSString *align; @property (nonatomic, assign) RNSVGVBMOS meetOrSlice; diff --git a/ios/Elements/RNSVGImage.m b/ios/Elements/RNSVGImage.m index 8a37ad104..a6723e94d 100644 --- a/ios/Elements/RNSVGImage.m +++ b/ios/Elements/RNSVGImage.m @@ -51,7 +51,7 @@ - (void)setSrc:(id)src - (void)setX:(NSString *)x { - if (x == _x) { + if ([x isEqualToString:_x]) { return; } [self invalidate]; @@ -60,34 +60,34 @@ - (void)setX:(NSString *)x - (void)setY:(NSString *)y { - if (y == _y) { + if ([y isEqualToString:_y]) { return; } [self invalidate]; _y = y; } -- (void)setWidth:(NSString *)width +- (void)setImagewidth:(NSString *)width { - if (width == _width) { + if ([width isEqualToString:_imagewidth]) { return; } [self invalidate]; - _width = width; + _imagewidth = width; } -- (void)setHeight:(NSString *)height +- (void)setImageheight:(NSString *)height { - if (height == _height) { + if ([height isEqualToString:_imageheight]) { return; } [self invalidate]; - _height = height; + _imageheight = height; } - (void)setAlign:(NSString *)align { - if (align == _align) { + if ([align isEqualToString:_align]) { return; } [self invalidate]; @@ -122,9 +122,9 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect CGRect imageBounds = CGRectMake(0, 0, _imageSize.width, _imageSize.height); CGAffineTransform viewbox = [RNSVGViewBox getTransform:imageBounds eRect:hitArea align:self.align meetOrSlice:self.meetOrSlice]; + [self clip:context]; CGContextTranslateCTM(context, 0, hitArea.size.height); CGContextScaleCTM(context, 1, -1); - [self clip:context]; CGContextClipToRect(context, hitArea); CGContextConcatCTM(context, viewbox); CGContextDrawImage(context, imageBounds, _image); @@ -135,8 +135,8 @@ - (CGRect)getHitArea { CGFloat x = [self relativeOnWidth:self.x]; CGFloat y = [self relativeOnHeight:self.y]; - CGFloat width = [self relativeOnWidth:self.width]; - CGFloat height = [self relativeOnHeight:self.height]; + CGFloat width = [self relativeOnWidth:self.imagewidth]; + CGFloat height = [self relativeOnHeight:self.imageheight]; if (width == 0) { width = _imageSize.width; } diff --git a/ios/Elements/RNSVGLinearGradient.m b/ios/Elements/RNSVGLinearGradient.m index 657ce5560..c6b6149b2 100644 --- a/ios/Elements/RNSVGLinearGradient.m +++ b/ios/Elements/RNSVGLinearGradient.m @@ -11,6 +11,47 @@ @implementation RNSVGLinearGradient + +- (void)setX1:(NSString *)x1 +{ + if ([x1 isEqualToString:_x1]) { + return; + } + + _x1 = x1; + [self invalidate]; +} + +- (void)setY1:(NSString *)y1 +{ + if ([y1 isEqualToString:_y1]) { + return; + } + + _y1 = y1; + [self invalidate]; +} + +- (void)setX2:(NSString *)x2 +{ + if ([x2 isEqualToString:_x2]) { + return; + } + + _x2 = x2; + [self invalidate]; +} + +- (void)setY2:(NSString *)y2 +{ + if ([y2 isEqualToString:_y2]) { + return; + } + + _y2 = y2; + [self invalidate]; +} + - (void)setGradient:(NSArray *)gradient { if (gradient == _gradient) { @@ -21,6 +62,22 @@ - (void)setGradient:(NSArray *)gradient [self invalidate]; } +- (void)setGradientUnits:(RNSVGUnits)gradientUnits +{ + if (gradientUnits == _gradientUnits) { + return; + } + + _gradientUnits = gradientUnits; + [self invalidate]; +} + +- (void)setGradientTransform:(CGAffineTransform)gradientTransform +{ + _gradientTransform = gradientTransform; + [self invalidate]; +} + - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { return nil; diff --git a/ios/Elements/RNSVGMask.h b/ios/Elements/RNSVGMask.h new file mode 100644 index 000000000..cd7e7efdc --- /dev/null +++ b/ios/Elements/RNSVGMask.h @@ -0,0 +1,14 @@ + +#import "RNSVGGroup.h" + +@interface RNSVGMask : RNSVGGroup + +@property (nonatomic, strong) NSString *x; +@property (nonatomic, strong) NSString *y; +@property (nonatomic, strong) NSString *maskwidth; +@property (nonatomic, strong) NSString *maskheight; +@property (nonatomic, assign) RNSVGUnits maskUnits; +@property (nonatomic, assign) RNSVGUnits maskContentUnits; +@property (nonatomic, assign) CGAffineTransform maskTransform; + +@end diff --git a/ios/Elements/RNSVGMask.m b/ios/Elements/RNSVGMask.m new file mode 100644 index 000000000..c3ceec927 --- /dev/null +++ b/ios/Elements/RNSVGMask.m @@ -0,0 +1,92 @@ +/** + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#import "RNSVGMask.h" +#import "RNSVGPainter.h" +#import "RNSVGBrushType.h" +#import "RNSVGNode.h" + +@implementation RNSVGMask + +- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event +{ + return nil; +} + +- (void)parseReference +{ + [self.svgView defineMask:self maskName:self.name]; +} + +- (void)setX:(NSString *)x +{ + if ([x isEqualToString:_x]) { + return; + } + + _x = x; + [self invalidate]; +} + +- (void)setY:(NSString *)y +{ + if ([y isEqualToString:_y]) { + return; + } + + _y = y; + [self invalidate]; +} + +- (void)setMaskwidth:(NSString *)maskwidth +{ + if ([maskwidth isEqualToString:_maskwidth]) { + return; + } + + _maskwidth = maskwidth; + [self invalidate]; +} + +- (void)setMaskheight:(NSString *)maskheight +{ + if ([maskheight isEqualToString:_maskheight]) { + return; + } + + _maskheight = maskheight; + [self invalidate]; +} + +- (void)setMaskUnits:(RNSVGUnits)maskUnits +{ + if (maskUnits == _maskUnits) { + return; + } + + _maskUnits = maskUnits; + [self invalidate]; +} + +- (void)setMaskContentUnits:(RNSVGUnits)maskContentUnits +{ + if (maskContentUnits == _maskContentUnits) { + return; + } + + _maskContentUnits = maskContentUnits; + [self invalidate]; +} + +- (void)setMaskTransform:(CGAffineTransform)maskTransform +{ + _maskTransform = maskTransform; + [self invalidate]; +} + +@end + diff --git a/ios/Elements/RNSVGPattern.m b/ios/Elements/RNSVGPattern.m new file mode 100644 index 000000000..84d8ee0e8 --- /dev/null +++ b/ios/Elements/RNSVGPattern.m @@ -0,0 +1,163 @@ +/** + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ +#import "RNSVGPattern.h" +#import "RNSVGPainter.h" +#import "RNSVGBrushType.h" +#import "RNSVGNode.h" + +@implementation RNSVGPattern + +- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event +{ + return nil; +} + +- (void)parseReference +{ + NSArray *points = @[self.x, self.y, self.patternwidth, self.patternheight]; + RNSVGPainter *painter = [[RNSVGPainter alloc] initWithPointsArray:points]; + [painter setUnits:self.patternUnits]; + [painter setContentUnits:self.patternContentUnits]; + [painter setTransform:self.patternTransform]; + [painter setPattern:self]; + + if (self.patternUnits == kRNSVGUnitsUserSpaceOnUse || self.patternContentUnits == kRNSVGUnitsUserSpaceOnUse) { + [painter setUserSpaceBoundingBox:[self.svgView getContextBounds]]; + } + + [self.svgView definePainter:painter painterName:self.name]; +} + +- (void)setX:(NSString *)x +{ + if ([x isEqualToString:_x]) { + return; + } + + _x = x; + [self invalidate]; +} + +- (void)setY:(NSString *)y +{ + if ([y isEqualToString:_y]) { + return; + } + + _y = y; + [self invalidate]; +} + +- (void)setPatternwidth:(NSString *)patternwidth +{ + if ([patternwidth isEqualToString:_patternwidth]) { + return; + } + + _patternwidth = patternwidth; + [self invalidate]; +} + +- (void)setPatternheight:(NSString *)patternheight +{ + if ([patternheight isEqualToString:_patternheight]) { + return; + } + + _patternheight = patternheight; + [self invalidate]; +} + +- (void)setPatternUnits:(RNSVGUnits)patternUnits +{ + if (patternUnits == _patternUnits) { + return; + } + + _patternUnits = patternUnits; + [self invalidate]; +} + +- (void)setPatternContentUnits:(RNSVGUnits)patternContentUnits +{ + if (patternContentUnits == _patternContentUnits) { + return; + } + + _patternContentUnits = patternContentUnits; + [self invalidate]; +} + +- (void)setPatternTransform:(CGAffineTransform)patternTransform +{ + _patternTransform = patternTransform; + [self invalidate]; +} + +- (void)setMinX:(CGFloat)minX +{ + if (minX == _minX) { + return; + } + + [self invalidate]; + _minX = minX; +} + +- (void)setMinY:(CGFloat)minY +{ + if (minY == _minY) { + return; + } + + [self invalidate]; + _minY = minY; +} + +- (void)setVbWidth:(CGFloat)vbWidth +{ + if (vbWidth == _vbWidth) { + return; + } + + [self invalidate]; + _vbWidth = vbWidth; +} + +- (void)setVbHeight:(CGFloat)vbHeight +{ + if (_vbHeight == vbHeight) { + return; + } + + [self invalidate]; + _vbHeight = vbHeight; +} + +- (void)setAlign:(NSString *)align +{ + if ([align isEqualToString:_align]) { + return; + } + + [self invalidate]; + _align = align; +} + +- (void)setMeetOrSlice:(RNSVGVBMOS)meetOrSlice +{ + if (meetOrSlice == _meetOrSlice) { + return; + } + + [self invalidate]; + _meetOrSlice = meetOrSlice; +} + +@end + diff --git a/ios/Elements/RNSVGRadialGradient.h b/ios/Elements/RNSVGRadialGradient.h index cb290f7df..50aa01c78 100644 --- a/ios/Elements/RNSVGRadialGradient.h +++ b/ios/Elements/RNSVGRadialGradient.h @@ -17,7 +17,7 @@ @property (nonatomic, strong) NSString *cx; @property (nonatomic, strong) NSString *cy; @property (nonatomic, copy) NSArray *gradient; -@property (nonatomic, assign)RNSVGUnits gradientUnits; -@property (nonatomic, assign)CGAffineTransform gradientTransform; +@property (nonatomic, assign) RNSVGUnits gradientUnits; +@property (nonatomic, assign) CGAffineTransform gradientTransform; @end diff --git a/ios/Elements/RNSVGRadialGradient.m b/ios/Elements/RNSVGRadialGradient.m index f214b5484..17a1e732f 100644 --- a/ios/Elements/RNSVGRadialGradient.m +++ b/ios/Elements/RNSVGRadialGradient.m @@ -9,6 +9,66 @@ @implementation RNSVGRadialGradient +- (void)setFx:(NSString *)fx +{ + if ([fx isEqualToString:_fx]) { + return; + } + + _fx = fx; + [self invalidate]; +} + +- (void)setFy:(NSString *)fy +{ + if ([fy isEqualToString:_fy]) { + return; + } + + _fy = fy; + [self invalidate]; +} + +- (void)setRx:(NSString *)rx +{ + if ([rx isEqualToString:_rx]) { + return; + } + + _rx = rx; + [self invalidate]; +} + +- (void)setRy:(NSString *)ry +{ + if ([ry isEqualToString:_ry]) { + return; + } + + _ry = ry; + [self invalidate]; +} + +- (void)setCx:(NSString *)cx +{ + if ([cx isEqualToString:_cx]) { + return; + } + + _cx = cx; + [self invalidate]; +} + +- (void)setCy:(NSString *)cy +{ + if ([cy isEqualToString:_cy]) { + return; + } + + _cy = cy; + [self invalidate]; +} + - (void)setGradient:(NSArray *)gradient { if (gradient == _gradient) { @@ -19,6 +79,22 @@ - (void)setGradient:(NSArray *)gradient [self invalidate]; } +- (void)setGradientUnits:(RNSVGUnits)gradientUnits +{ + if (gradientUnits == _gradientUnits) { + return; + } + + _gradientUnits = gradientUnits; + [self invalidate]; +} + +- (void)setGradientTransform:(CGAffineTransform)gradientTransform +{ + _gradientTransform = gradientTransform; + [self invalidate]; +} + - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { return nil; diff --git a/ios/Elements/RNSVGSvgView.h b/ios/Elements/RNSVGSvgView.h index 031f2cb5a..83201b44c 100644 --- a/ios/Elements/RNSVGSvgView.h +++ b/ios/Elements/RNSVGSvgView.h @@ -46,6 +46,10 @@ - (RNSVGPainter *)getDefinedPainter:(NSString *)painterName; +- (void)defineMask:(RNSVGNode *)mask maskName:(NSString *)maskName; + +- (RNSVGNode *)getDefinedMask:(NSString *)maskName; + - (NSString *)getDataURL; - (CGRect)getContextBounds; @@ -54,4 +58,6 @@ - (void)drawToContext:(CGContextRef)context withRect:(CGRect)rect; +- (CGAffineTransform)getViewBoxTransform; + @end diff --git a/ios/Elements/RNSVGSvgView.m b/ios/Elements/RNSVGSvgView.m index 833c84419..e4aabef7c 100644 --- a/ios/Elements/RNSVGSvgView.m +++ b/ios/Elements/RNSVGSvgView.m @@ -16,18 +16,21 @@ @implementation RNSVGSvgView NSMutableDictionary *_clipPaths; NSMutableDictionary *_templates; NSMutableDictionary *_painters; + NSMutableDictionary *_masks; CGAffineTransform _viewBoxTransform; CGAffineTransform _invviewBoxTransform; + bool rendered; } - (instancetype)initWithFrame:(CGRect)frame { - if (self = [super initWithFrame:frame]) { - // This is necessary to ensure that [self setNeedsDisplay] actually triggers - // a redraw when our parent transitions between hidden and visible. - self.contentMode = UIViewContentModeRedraw; - } - return self; + if (self = [super initWithFrame:frame]) { + // This is necessary to ensure that [self setNeedsDisplay] actually triggers + // a redraw when our parent transitions between hidden and visible. + self.contentMode = UIViewContentModeRedraw; + } + rendered = false; + return self; } - (void)insertReactSubview:(UIView *)subview atIndex:(NSInteger)atIndex @@ -48,6 +51,20 @@ - (void)didUpdateReactSubviews // Do nothing, as subviews are inserted by insertReactSubview: } +- (void)releaseCachedPath +{ + if (!rendered) { + return; + } + rendered = false; + for (UIView *node in self.subviews) { + if ([node isKindOfClass:[RNSVGNode class]]) { + RNSVGNode *n = (RNSVGNode *)node; + [n releaseCachedPath]; + } + }; +} + - (void)invalidate { [self setNeedsDisplay]; @@ -60,6 +77,7 @@ - (void)setMinX:(CGFloat)minX } [self invalidate]; + [self releaseCachedPath]; _minX = minX; } @@ -70,6 +88,7 @@ - (void)setMinY:(CGFloat)minY } [self invalidate]; + [self releaseCachedPath]; _minY = minY; } @@ -80,6 +99,7 @@ - (void)setVbWidth:(CGFloat)vbWidth } [self invalidate]; + [self releaseCachedPath]; _vbWidth = vbWidth; } @@ -90,26 +110,29 @@ - (void)setVbHeight:(CGFloat)vbHeight } [self invalidate]; + [self releaseCachedPath]; _vbHeight = vbHeight; } -- (void)setBBWidth:(NSString *)bbWidth +- (void)setBbWidth:(NSString *)bbWidth { if ([bbWidth isEqualToString:_bbWidth]) { return; } [self invalidate]; + [self releaseCachedPath]; _bbWidth = bbWidth; } -- (void)setBBHeight:(NSString *)bbHeight +- (void)setBbHeight:(NSString *)bbHeight { if ([bbHeight isEqualToString:_bbHeight]) { return; } [self invalidate]; + [self releaseCachedPath]; _bbHeight = bbHeight; } @@ -120,6 +143,7 @@ - (void)setAlign:(NSString *)align } [self invalidate]; + [self releaseCachedPath]; _align = align; } @@ -130,6 +154,7 @@ - (void)setMeetOrSlice:(RNSVGVBMOS)meetOrSlice } [self invalidate]; + [self releaseCachedPath]; _meetOrSlice = meetOrSlice; } @@ -159,6 +184,7 @@ - (void)drawToContext:(CGContextRef)context withRect:(CGRect)rect { - (void)drawRect:(CGRect)rect { + rendered = true; _clipPaths = nil; _templates = nil; _painters = nil; @@ -263,9 +289,27 @@ - (RNSVGPainter *)getDefinedPainter:(NSString *)painterName; return _painters ? [_painters objectForKey:painterName] : nil; } +- (void)defineMask:(RNSVGNode *)mask maskName:(NSString *)maskName +{ + if (!_masks) { + _masks = [[NSMutableDictionary alloc] init]; + } + [_masks setObject:mask forKey:maskName]; +} + +- (RNSVGNode *)getDefinedMask:(NSString *)maskName; +{ + return _masks ? [_masks objectForKey:maskName] : nil; +} + - (CGRect)getContextBounds { return CGContextGetClipBoundingBox(UIGraphicsGetCurrentContext()); } +- (CGAffineTransform)getViewBoxTransform +{ + return _viewBoxTransform; +} + @end diff --git a/ios/Elements/RNSVGUse.h b/ios/Elements/RNSVGUse.h index 6d8c7d754..1e786e509 100644 --- a/ios/Elements/RNSVGUse.h +++ b/ios/Elements/RNSVGUse.h @@ -15,6 +15,6 @@ @interface RNSVGUse : RNSVGRenderable @property (nonatomic, strong) NSString *href; -@property (nonatomic, strong) NSString *width; -@property (nonatomic, strong) NSString *height; +@property (nonatomic, strong) NSString *usewidth; +@property (nonatomic, strong) NSString *useheight; @end diff --git a/ios/Elements/RNSVGUse.m b/ios/Elements/RNSVGUse.m index f21182939..f278dde26 100644 --- a/ios/Elements/RNSVGUse.m +++ b/ios/Elements/RNSVGUse.m @@ -13,7 +13,7 @@ @implementation RNSVGUse - (void)setHref:(NSString *)href { - if (href == _href) { + if ([href isEqualToString:_href]) { return; } @@ -21,6 +21,25 @@ - (void)setHref:(NSString *)href _href = href; } +- (void)setUsewidth:(NSString *)usewidth +{ + if ([usewidth isEqualToString:_usewidth]) { + return; + } + + [self invalidate]; + _usewidth = usewidth; +} + +- (void)setUseheight:(NSString *)useheight +{ + if ([useheight isEqualToString:_useheight]) { + return; + } + + [self invalidate]; + _useheight = useheight; +} - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect { @@ -28,22 +47,22 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect if (template) { [self beginTransparencyLayer:context]; [self clip:context]; - + if ([template isKindOfClass:[RNSVGRenderable class]]) { [(RNSVGRenderable*)template mergeProperties:self]; } if ([template class] == [RNSVGSymbol class]) { RNSVGSymbol *symbol = (RNSVGSymbol*)template; - [symbol renderSymbolTo:context width:[self relativeOnWidth:self.width] height:[self relativeOnWidth:self.height]]; + [symbol renderSymbolTo:context width:[self relativeOnWidth:self.usewidth] height:[self relativeOnHeight:self.useheight]]; } else { [template renderTo:context rect:rect]; } - + if ([template isKindOfClass:[RNSVGRenderable class]]) { [(RNSVGRenderable*)template resetProperties]; } - + [self endTransparencyLayer:context]; } else if (self.href) { // TODO: calling yellow box here diff --git a/ios/RNSVG.xcodeproj/project.pbxproj b/ios/RNSVG.xcodeproj/project.pbxproj index 182aa5475..273d1ca06 100644 --- a/ios/RNSVG.xcodeproj/project.pbxproj +++ b/ios/RNSVG.xcodeproj/project.pbxproj @@ -58,6 +58,14 @@ 7FC260CE1E3499BC00A39833 /* RNSVGViewBox.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FC260CD1E3499BC00A39833 /* RNSVGViewBox.m */; }; 7FC260D11E34A12000A39833 /* RNSVGSymbol.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FC260D01E34A12000A39833 /* RNSVGSymbol.m */; }; 7FC260D41E34A12A00A39833 /* RNSVGSymbolManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FC260D31E34A12A00A39833 /* RNSVGSymbolManager.m */; }; + 94241666213B0D4500088E93 /* RNSVGPattern.m in Sources */ = {isa = PBXBuildFile; fileRef = 94241665213B0D4500088E93 /* RNSVGPattern.m */; }; + 94241667213B0D4500088E93 /* RNSVGPattern.m in Sources */ = {isa = PBXBuildFile; fileRef = 94241665213B0D4500088E93 /* RNSVGPattern.m */; }; + 9424166D213B302600088E93 /* RNSVGPatternManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 9424166C213B302600088E93 /* RNSVGPatternManager.m */; }; + 9424166E213B302600088E93 /* RNSVGPatternManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 9424166C213B302600088E93 /* RNSVGPatternManager.m */; }; + 947F380B214810DC00677F2A /* RNSVGMask.m in Sources */ = {isa = PBXBuildFile; fileRef = 947F380A214810DC00677F2A /* RNSVGMask.m */; }; + 947F380C214810DC00677F2A /* RNSVGMask.m in Sources */ = {isa = PBXBuildFile; fileRef = 947F380A214810DC00677F2A /* RNSVGMask.m */; }; + 947F380F2148119A00677F2A /* RNSVGMaskManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 947F380E2148119A00677F2A /* RNSVGMaskManager.m */; }; + 947F38102148119A00677F2A /* RNSVGMaskManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 947F380E2148119A00677F2A /* RNSVGMaskManager.m */; }; 9494C4D81F473BA700D5BCFD /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9494C4D71F473BA700D5BCFD /* QuartzCore.framework */; }; 9494C4DA1F473BCB00D5BCFD /* CoreText.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9494C4D91F473BCB00D5BCFD /* CoreText.framework */; }; 9494C4DC1F473BD900D5BCFD /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9494C4DB1F473BD900D5BCFD /* CoreGraphics.framework */; }; @@ -238,6 +246,14 @@ 7FC260D01E34A12000A39833 /* RNSVGSymbol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RNSVGSymbol.m; path = Elements/RNSVGSymbol.m; sourceTree = ""; }; 7FC260D21E34A12A00A39833 /* RNSVGSymbolManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNSVGSymbolManager.h; sourceTree = ""; }; 7FC260D31E34A12A00A39833 /* RNSVGSymbolManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNSVGSymbolManager.m; sourceTree = ""; }; + 94241665213B0D4500088E93 /* RNSVGPattern.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RNSVGPattern.m; path = Elements/RNSVGPattern.m; sourceTree = ""; }; + 94241669213B0DB800088E93 /* RNSVGPattern.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RNSVGPattern.h; sourceTree = ""; }; + 9424166A213B2FF100088E93 /* RNSVGPatternManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RNSVGPatternManager.h; sourceTree = ""; }; + 9424166C213B302600088E93 /* RNSVGPatternManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RNSVGPatternManager.m; sourceTree = ""; }; + 947F3809214810B800677F2A /* RNSVGMask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RNSVGMask.h; path = Elements/RNSVGMask.h; sourceTree = ""; }; + 947F380A214810DC00677F2A /* RNSVGMask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RNSVGMask.m; path = Elements/RNSVGMask.m; sourceTree = ""; }; + 947F380D2148118300677F2A /* RNSVGMaskManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNSVGMaskManager.h; sourceTree = ""; }; + 947F380E2148119A00677F2A /* RNSVGMaskManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNSVGMaskManager.m; sourceTree = ""; }; 9494C4D71F473BA700D5BCFD /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; 9494C4D91F473BCB00D5BCFD /* CoreText.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreText.framework; path = System/Library/Frameworks/CoreText.framework; sourceTree = SDKROOT; }; 9494C4DB1F473BD900D5BCFD /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; @@ -334,6 +350,10 @@ 7F08CE971E23476900650F83 /* RNSVGTextPathManager.m */, 7F08CE981E23476900650F83 /* RNSVGTSpanManager.h */, 7F08CE991E23476900650F83 /* RNSVGTSpanManager.m */, + 9424166A213B2FF100088E93 /* RNSVGPatternManager.h */, + 9424166C213B302600088E93 /* RNSVGPatternManager.m */, + 947F380D2148118300677F2A /* RNSVGMaskManager.h */, + 947F380E2148119A00677F2A /* RNSVGMaskManager.m */, 10BEC1BE1D3F680F00FDCB19 /* RNSVGLinearGradientManager.h */, 10BEC1BF1D3F680F00FDCB19 /* RNSVGLinearGradientManager.m */, 10BEC1C01D3F680F00FDCB19 /* RNSVGRadialGradientManager.h */, @@ -413,6 +433,10 @@ 7FC260D01E34A12000A39833 /* RNSVGSymbol.m */, 10BEC1B81D3F66F500FDCB19 /* RNSVGLinearGradient.h */, 10BEC1B91D3F66F500FDCB19 /* RNSVGLinearGradient.m */, + 94241669213B0DB800088E93 /* RNSVGPattern.h */, + 94241665213B0D4500088E93 /* RNSVGPattern.m */, + 947F3809214810B800677F2A /* RNSVGMask.h */, + 947F380A214810DC00677F2A /* RNSVGMask.m */, 10BEC1BA1D3F66F500FDCB19 /* RNSVGRadialGradient.h */, 10BEC1BB1D3F66F500FDCB19 /* RNSVGRadialGradient.m */, 1023B4911D3DF5060051496D /* RNSVGUse.h */, @@ -543,8 +567,10 @@ B56895AA20352B36004DBF1E /* RNSVGBezierElement.m in Sources */, 10BA0D3F1CE74E3100887C2B /* RNSVGTextManager.m in Sources */, 1039D28A1CE71EB7001E90A8 /* RNSVGImage.m in Sources */, + 94241666213B0D4500088E93 /* RNSVGPattern.m in Sources */, 10BA0D4B1CE74E3D00887C2B /* RNSVGRect.m in Sources */, 10BA0D341CE74E3100887C2B /* RNSVGCircleManager.m in Sources */, + 947F380B214810DC00677F2A /* RNSVGMask.m in Sources */, 10BEC1BC1D3F66F500FDCB19 /* RNSVGLinearGradient.m in Sources */, 1039D2B01CE72F27001E90A8 /* RNSVGPercentageConverter.m in Sources */, 10BA0D491CE74E3D00887C2B /* RNSVGEllipse.m in Sources */, @@ -580,11 +606,13 @@ 7FC260D41E34A12A00A39833 /* RNSVGSymbolManager.m in Sources */, 7F9CDAFA1E1F809C00E0C805 /* RNSVGPathParser.m in Sources */, 10BA0D361CE74E3100887C2B /* RNSVGGroupManager.m in Sources */, + 9424166D213B302600088E93 /* RNSVGPatternManager.m in Sources */, 7F08CE9A1E23476900650F83 /* RNSVGTextPathManager.m in Sources */, 7F08CE9B1E23476900650F83 /* RNSVGTSpanManager.m in Sources */, B56895B120352B9C004DBF1E /* RNSVGPropHelper.m in Sources */, 7FC260CE1E3499BC00A39833 /* RNSVGViewBox.m in Sources */, 7F08CEA11E23479700650F83 /* RNSVGTSpan.m in Sources */, + 947F380F2148119A00677F2A /* RNSVGMaskManager.m in Sources */, 10BA0D4A1CE74E3D00887C2B /* RNSVGLine.m in Sources */, 10FDEEB21D3FB60500A5C46C /* RNSVGPainterBrush.m in Sources */, 1039D28C1CE71EB7001E90A8 /* RNSVGSvgView.m in Sources */, @@ -601,8 +629,10 @@ A361E76E1EB0C33D00646005 /* RNSVGTextManager.m in Sources */, A361E76F1EB0C33D00646005 /* RNSVGImage.m in Sources */, A361E7701EB0C33D00646005 /* RNSVGRect.m in Sources */, + 94241667213B0D4500088E93 /* RNSVGPattern.m in Sources */, A361E7711EB0C33D00646005 /* RNSVGCircleManager.m in Sources */, A361E7721EB0C33D00646005 /* RNSVGLinearGradient.m in Sources */, + 947F380C214810DC00677F2A /* RNSVGMask.m in Sources */, A361E7731EB0C33D00646005 /* RNSVGPercentageConverter.m in Sources */, A361E7751EB0C33D00646005 /* RNSVGEllipse.m in Sources */, A361E7761EB0C33D00646005 /* RNSVGPath.m in Sources */, @@ -638,11 +668,13 @@ A361E7921EB0C33D00646005 /* RNSVGSymbolManager.m in Sources */, A361E7931EB0C33D00646005 /* RNSVGPathParser.m in Sources */, A361E7941EB0C33D00646005 /* RNSVGGroupManager.m in Sources */, + 9424166E213B302600088E93 /* RNSVGPatternManager.m in Sources */, A361E7951EB0C33D00646005 /* RNSVGTextPathManager.m in Sources */, 167AF45B2087C2A10035AA75 /* RNSVGTextProperties.m in Sources */, A361E7961EB0C33D00646005 /* RNSVGTSpanManager.m in Sources */, A361E7971EB0C33D00646005 /* RNSVGViewBox.m in Sources */, A361E7981EB0C33D00646005 /* RNSVGTSpan.m in Sources */, + 947F38102148119A00677F2A /* RNSVGMaskManager.m in Sources */, A361E7991EB0C33D00646005 /* RNSVGLine.m in Sources */, 167AF4582087C2910035AA75 /* RNSVGFontData.m in Sources */, A361E79A1EB0C33D00646005 /* RNSVGPainterBrush.m in Sources */, diff --git a/ios/RNSVGNode.h b/ios/RNSVGNode.h index d90e6a33f..65ceeae5a 100644 --- a/ios/RNSVGNode.h +++ b/ios/RNSVGNode.h @@ -30,6 +30,7 @@ extern CGFloat const RNSVG_DEFAULT_FONT_SIZE; @property (nonatomic, assign) CGFloat opacity; @property (nonatomic, assign) RNSVGCGFCRule clipRule; @property (nonatomic, strong) NSString *clipPath; +@property (nonatomic, strong) NSString *mask; @property (nonatomic, assign) BOOL responsible; @property (nonatomic, assign) CGAffineTransform matrix; @property (nonatomic, assign) CGAffineTransform invmatrix; @@ -90,10 +91,6 @@ extern CGFloat const RNSVG_DEFAULT_FONT_SIZE; - (CGFloat)getContextHeight; -- (CGFloat)getContextLeft; - -- (CGFloat)getContextTop; - /** * save element`s reference into svg element. */ @@ -105,4 +102,6 @@ extern CGFloat const RNSVG_DEFAULT_FONT_SIZE; - (void)traverseSubviews:(BOOL (^)(__kindof UIView *node))block; +- (void)releaseCachedPath; + @end diff --git a/ios/RNSVGNode.m b/ios/RNSVGNode.m index adccc2527..aadf02474 100644 --- a/ios/RNSVGNode.m +++ b/ios/RNSVGNode.m @@ -22,6 +22,7 @@ @implementation RNSVGNode RNSVGGlyphContext *glyphContext; BOOL _transparent; CGPathRef _cachedClipPath; + CGImageRef _clipMask; } CGFloat const RNSVG_M_SQRT1_2l = 0.707106781186547524400844362104849039; @@ -57,6 +58,11 @@ - (void)invalidate { id container = (id)self.superview; [container invalidate]; + [self clearPath]; +} + +- (void)clearPath +{ if (_path) { CGPathRelease(_path); _path = nil; @@ -117,6 +123,16 @@ - (void)reactSetInheritedBackgroundColor:(UIColor *)inheritedBackgroundColor self.backgroundColor = inheritedBackgroundColor; } +- (void)setName:(NSString *)name +{ + if ([name isEqualToString:_name]) { + return; + } + + [self invalidate]; + _name = name; +} + - (void)setOpacity:(CGFloat)opacity { if (opacity == _opacity) { @@ -165,12 +181,36 @@ - (void)setClientRect:(CGRect)clientRect { - (void)setClipPath:(NSString *)clipPath { - if (_clipPath == clipPath) { + if ([_clipPath isEqualToString:clipPath]) { return; } CGPathRelease(_cachedClipPath); + CGImageRelease(_clipMask); _cachedClipPath = nil; _clipPath = clipPath; + _clipMask = nil; + [self invalidate]; +} + +- (void)setClipRule:(RNSVGCGFCRule)clipRule +{ + if (_clipRule == clipRule) { + return; + } + CGPathRelease(_cachedClipPath); + CGImageRelease(_clipMask); + _cachedClipPath = nil; + _clipRule = clipRule; + _clipMask = nil; + [self invalidate]; +} + +- (void)setMask:(NSString *)mask +{ + if ([_mask isEqualToString:mask]) { + return; + } + _mask = mask; [self invalidate]; } @@ -201,10 +241,29 @@ - (CGPathRef)getClipPath - (CGPathRef)getClipPath:(CGContextRef)context { if (self.clipPath) { - _cachedClipPath = CGPathRetain([[self.svgView getDefinedClipPath:self.clipPath] getPath:context]); + RNSVGClipPath *_clipNode = (RNSVGClipPath*)[self.svgView getDefinedClipPath:self.clipPath]; + _cachedClipPath = CGPathRetain([_clipNode getPath:context]); + if (_clipMask) { + CGImageRelease(_clipMask); + } + if ([_clipNode isSimpleClipPath]) { + _clipMask = nil; + } else { + CGRect bounds = CGContextGetClipBoundingBox(context); + CGSize size = bounds.size; + + UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); + CGContextRef newContext = UIGraphicsGetCurrentContext(); + CGContextTranslateCTM(newContext, 0.0, size.height); + CGContextScaleCTM(newContext, 1.0, -1.0); + + [_clipNode renderLayerTo:newContext rect:bounds]; + _clipMask = CGBitmapContextCreateImage(newContext); + UIGraphicsEndImageContext(); + } } - return [self getClipPath]; + return _cachedClipPath; } - (void)clip:(CGContextRef)context @@ -212,11 +271,16 @@ - (void)clip:(CGContextRef)context CGPathRef clipPath = [self getClipPath:context]; if (clipPath) { - CGContextAddPath(context, clipPath); - if (self.clipRule == kRNSVGCGFCRuleEvenodd) { - CGContextEOClip(context); + if (!_clipMask) { + CGContextAddPath(context, clipPath); + if (self.clipRule == kRNSVGCGFCRuleEvenodd) { + CGContextEOClip(context); + } else { + CGContextClip(context); + } } else { - CGContextClip(context); + CGRect bounds = CGContextGetClipBoundingBox(context); + CGContextClipToMask(context, bounds, _clipMask); } } } @@ -279,8 +343,9 @@ - (CGFloat)relativeOnHeight:(NSString *)length - (CGFloat)relativeOnOther:(NSString *)length { - CGFloat width = [self getContextWidth]; - CGFloat height = [self getContextHeight]; + CGRect bounds = [self getContextBounds]; + CGFloat width = CGRectGetWidth(bounds); + CGFloat height = CGRectGetHeight(bounds); CGFloat powX = width * width; CGFloat powY = height * height; CGFloat r = sqrt(powX + powY) * RNSVG_M_SQRT1_2l; @@ -291,36 +356,19 @@ - (CGFloat)relativeOnOther:(NSString *)length fontSize:[self getFontSizeFromContext]]; } -- (CGFloat)getContextWidth -{ - RNSVGGroup * root = self.textRoot; - RNSVGGlyphContext * gc = [root getGlyphContext]; - if (root == nil || gc == nil) { - return CGRectGetWidth([self.svgView getContextBounds]); - } else { - return [gc getWidth]; - } -} - -- (CGFloat)getContextHeight +- (CGRect)getContextBounds { - RNSVGGroup * root = self.textRoot; - RNSVGGlyphContext * gc = [root getGlyphContext]; - if (root == nil || gc == nil) { - return CGRectGetHeight([self.svgView getContextBounds]); - } else { - return [gc getHeight]; - } + return CGContextGetClipBoundingBox(UIGraphicsGetCurrentContext()); } -- (CGFloat)getContextLeft +- (CGFloat)getContextWidth { - return CGRectGetMinX([self.svgView getContextBounds]); + return CGRectGetWidth([self getContextBounds]); } -- (CGFloat)getContextTop +- (CGFloat)getContextHeight { - return CGRectGetMinY([self.svgView getContextBounds]); + return CGRectGetHeight([self getContextBounds]); } - (void)parseReference @@ -340,9 +388,22 @@ - (void)traverseSubviews:(BOOL (^)(__kindof UIView *node))block } } +- (void)releaseCachedPath +{ + [self clearPath]; + [self traverseSubviews:^BOOL(__kindof RNSVGNode *node) { + if ([node isKindOfClass:[RNSVGNode class]]) { + [node releaseCachedPath]; + } + return YES; + }]; +} + - (void)dealloc { CGPathRelease(_cachedClipPath); + CGImageRelease(_clipMask); + _clipMask = nil; } @end diff --git a/ios/RNSVGPattern.h b/ios/RNSVGPattern.h new file mode 100644 index 000000000..36db325e9 --- /dev/null +++ b/ios/RNSVGPattern.h @@ -0,0 +1,21 @@ + +#import "RNSVGGroup.h" + +@interface RNSVGPattern : RNSVGGroup + +@property (nonatomic, strong) NSString *x; +@property (nonatomic, strong) NSString *y; +@property (nonatomic, strong) NSString *patternwidth; +@property (nonatomic, strong) NSString *patternheight; +@property (nonatomic, assign)RNSVGUnits patternUnits; +@property (nonatomic, assign)RNSVGUnits patternContentUnits; +@property (nonatomic, assign)CGAffineTransform patternTransform; + +@property (nonatomic, assign) CGFloat minX; +@property (nonatomic, assign) CGFloat minY; +@property (nonatomic, assign) CGFloat vbWidth; +@property (nonatomic, assign) CGFloat vbHeight; +@property (nonatomic, strong) NSString *align; +@property (nonatomic, assign) RNSVGVBMOS meetOrSlice; + +@end diff --git a/ios/RNSVGRenderable.m b/ios/RNSVGRenderable.m index 98ee006e3..f7471d3a5 100644 --- a/ios/RNSVGRenderable.m +++ b/ios/RNSVGRenderable.m @@ -7,6 +7,9 @@ */ #import "RNSVGRenderable.h" +#import "RNSVGClipPath.h" +#import "RNSVGMask.h" +#import "RNSVGViewBox.h" @implementation RNSVGRenderable { @@ -74,7 +77,7 @@ - (void)setStrokeOpacity:(CGFloat)strokeOpacity - (void)setStrokeWidth:(NSString*)strokeWidth { - if (strokeWidth == _strokeWidth) { + if ([strokeWidth isEqualToString:_strokeWidth]) { return; } [self invalidate]; @@ -158,6 +161,11 @@ - (void)dealloc } } + +UInt32 saturate(double value) { + return value <= 0 ? 0 : value >= 255 ? 255 : value; +} + - (void)renderTo:(CGContextRef)context rect:(CGRect)rect { // This needs to be painted on a layer before being composited. @@ -166,7 +174,97 @@ - (void)renderTo:(CGContextRef)context rect:(CGRect)rect CGContextSetAlpha(context, self.opacity); [self beginTransparencyLayer:context]; - [self renderLayerTo:context rect:rect]; + + if (self.mask) { + // https://www.w3.org/TR/SVG11/masking.html#MaskElement + RNSVGMask *_maskNode = (RNSVGMask*)[self.svgView getDefinedMask:self.mask]; + CGRect bounds = CGContextGetClipBoundingBox(context); + CGSize boundsSize = bounds.size; + float height = boundsSize.height; + float width = boundsSize.width; + NSUInteger iheight = height; + NSUInteger iwidth = width; + NSUInteger npixels = iheight * iwidth; + CGRect drawBounds = CGRectMake(0, 0, width, height); + + // Allocate pixel buffer and bitmap context for mask + NSUInteger bytesPerPixel = 4; + NSUInteger bitsPerComponent = 8; + NSUInteger bytesPerRow = bytesPerPixel * iwidth; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + UInt32 * pixels = (UInt32 *) calloc(npixels, sizeof(UInt32)); + CGContextRef bcontext = CGBitmapContextCreate(pixels, iwidth, iheight, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); + + // Clip to mask bounds and render the mask + CGFloat x = [RNSVGPercentageConverter stringToFloat:[_maskNode x] + relative:width + offset:0]; + CGFloat y = [RNSVGPercentageConverter stringToFloat:[_maskNode y] + relative:height + offset:0]; + CGFloat w = [RNSVGPercentageConverter stringToFloat:[_maskNode maskwidth] + relative:width + offset:0]; + CGFloat h = [RNSVGPercentageConverter stringToFloat:[_maskNode maskheight] + relative:height + offset:0]; + CGRect maskBounds = CGRectMake(x, y, w, h); + CGContextClipToRect(bcontext, maskBounds); + [_maskNode renderLayerTo:bcontext rect:rect]; + + // Apply luminanceToAlpha filter primitive + // https://www.w3.org/TR/SVG11/filters.html#feColorMatrixElement + UInt32 * currentPixel = pixels; + for (NSUInteger i = 0; i < npixels; i++) { + UInt32 color = *currentPixel; + + UInt32 r = color & 0xFF; + UInt32 g = (color >> 8) & 0xFF; + UInt32 b = (color >> 16) & 0xFF; + + double luma = 0.299 * r + 0.587 * g + 0.144 * b; + *currentPixel = saturate(luma) << 24; + currentPixel++; + } + + // Create mask image and release memory + CGImageRef maskImage = CGBitmapContextCreateImage(bcontext); + CGColorSpaceRelease(colorSpace); + CGContextRelease(bcontext); + free(pixels); + + // Render content of current SVG Renderable to image + UIGraphicsBeginImageContextWithOptions(boundsSize, NO, 0.0); + CGContextRef newContext = UIGraphicsGetCurrentContext(); + CGContextTranslateCTM(newContext, 0.0, height); + CGContextScaleCTM(newContext, 1.0, -1.0); + [self renderLayerTo:newContext rect:rect]; + CGImageRef contentImage = CGBitmapContextCreateImage(newContext); + UIGraphicsEndImageContext(); + + // Blend current element and mask + UIGraphicsBeginImageContextWithOptions(boundsSize, NO, 0.0); + newContext = UIGraphicsGetCurrentContext(); + CGContextTranslateCTM(newContext, 0.0, height); + CGContextScaleCTM(newContext, 1.0, -1.0); + + CGContextSetBlendMode(newContext, kCGBlendModeCopy); + CGContextDrawImage(newContext, drawBounds, maskImage); + CGImageRelease(maskImage); + + CGContextSetBlendMode(newContext, kCGBlendModeSourceIn); + CGContextDrawImage(newContext, drawBounds, contentImage); + CGImageRelease(contentImage); + + CGImageRef blendedImage = CGBitmapContextCreateImage(newContext); + UIGraphicsEndImageContext(); + + // Render blended result into current render context + CGContextDrawImage(context, drawBounds, blendedImage); + CGImageRelease(blendedImage); + } else { + [self renderLayerTo:context rect:rect]; + } [self endTransparencyLayer:context]; CGContextRestoreGState(context); @@ -187,7 +285,7 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect self.path = CGPathRetain(CFAutorelease(CGPathCreateCopy([self getPath:context]))); [self setHitArea:self.path]; } - + const CGRect pathBounding = CGPathGetBoundingBox(self.path); const CGAffineTransform svgToClientTransform = CGAffineTransformConcat(CGContextGetCTM(context), self.svgView.invInitialCTM); self.clientRect = CGRectApplyAffineTransform(pathBounding, svgToClientTransform); @@ -210,6 +308,7 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect [self.fill paint:context opacity:self.fillOpacity painter:[self.svgView getDefinedPainter:self.fill.brushRef] + bounds:pathBounding ]; CGContextRestoreGState(context); @@ -255,6 +354,7 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect [self.stroke paint:context opacity:self.strokeOpacity painter:[self.svgView getDefinedPainter:self.stroke.brushRef] + bounds:pathBounding ]; return; } @@ -270,7 +370,7 @@ - (void)setHitArea:(CGPathRef)path _hitArea = nil; // Add path to hitArea CGMutablePathRef hitArea = CGPathCreateMutableCopy(path); - + if (self.stroke && self.strokeWidth) { // Add stroke to hitArea CGFloat width = [self relativeOnOther:self.strokeWidth]; @@ -278,7 +378,7 @@ - (void)setHitArea:(CGPathRef)path CGPathAddPath(hitArea, nil, strokePath); CGPathRelease(strokePath); } - + _hitArea = CGPathRetain(CFAutorelease(CGPathCreateCopy(hitArea))); CGPathRelease(hitArea); @@ -304,9 +404,19 @@ - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event return nil; } - CGPathRef clipPath = [self getClipPath]; - if (clipPath && !CGPathContainsPoint(clipPath, nil, transformed, self.clipRule == kRNSVGCGFCRuleEvenodd)) { - return nil; + if (self.clipPath) { + RNSVGClipPath *clipNode = (RNSVGClipPath*)[self.svgView getDefinedClipPath:self.clipPath]; + if ([clipNode isSimpleClipPath]) { + CGPathRef clipPath = [self getClipPath]; + if (clipPath && !CGPathContainsPoint(clipPath, nil, transformed, self.clipRule == kRNSVGCGFCRuleEvenodd)) { + return nil; + } + } else { + RNSVGRenderable *clipGroup = (RNSVGRenderable*)clipNode; + if (![clipGroup hitTest:transformed withEvent:event]) { + return nil; + } + } } return self; diff --git a/ios/Shapes/RNSVGCircle.m b/ios/Shapes/RNSVGCircle.m index f4095e22f..47305a094 100644 --- a/ios/Shapes/RNSVGCircle.m +++ b/ios/Shapes/RNSVGCircle.m @@ -13,7 +13,7 @@ @implementation RNSVGCircle - (void)setCx:(NSString *)cx { - if (cx == _cx) { + if ([cx isEqualToString:_cx]) { return; } [self invalidate]; @@ -22,7 +22,7 @@ - (void)setCx:(NSString *)cx - (void)setCy:(NSString *)cy { - if (cy == _cy) { + if ([cy isEqualToString:_cy]) { return; } [self invalidate]; @@ -31,7 +31,7 @@ - (void)setCy:(NSString *)cy - (void)setR:(NSString *)r { - if (r == _r) { + if ([r isEqualToString:_r]) { return; } [self invalidate]; diff --git a/ios/Shapes/RNSVGEllipse.m b/ios/Shapes/RNSVGEllipse.m index 6a26176ab..206e2e78e 100644 --- a/ios/Shapes/RNSVGEllipse.m +++ b/ios/Shapes/RNSVGEllipse.m @@ -13,7 +13,7 @@ @implementation RNSVGEllipse - (void)setCx:(NSString *)cx { - if (cx == _cx) { + if ([cx isEqualToString:_cx]) { return; } [self invalidate]; @@ -22,7 +22,7 @@ - (void)setCx:(NSString *)cx - (void)setCy:(NSString *)cy { - if (cy == _cy) { + if ([cy isEqualToString:_cy]) { return; } [self invalidate]; @@ -31,7 +31,7 @@ - (void)setCy:(NSString *)cy - (void)setRx:(NSString *)rx { - if (rx == _rx) { + if ([rx isEqualToString:_rx]) { return; } [self invalidate]; @@ -40,7 +40,7 @@ - (void)setRx:(NSString *)rx - (void)setRy:(NSString *)ry { - if (ry == _ry) { + if ([ry isEqualToString:_ry]) { return; } [self invalidate]; diff --git a/ios/Shapes/RNSVGLine.m b/ios/Shapes/RNSVGLine.m index 5e23d4d03..97a72b3f6 100644 --- a/ios/Shapes/RNSVGLine.m +++ b/ios/Shapes/RNSVGLine.m @@ -13,7 +13,7 @@ @implementation RNSVGLine - (void)setX1:(NSString *)x1 { - if (x1 == _x1) { + if ([x1 isEqualToString:_x1]) { return; } [self invalidate]; @@ -22,7 +22,7 @@ - (void)setX1:(NSString *)x1 - (void)setY1:(NSString *)y1 { - if (y1 == _y1) { + if ([y1 isEqualToString:_y1]) { return; } [self invalidate]; @@ -31,7 +31,7 @@ - (void)setY1:(NSString *)y1 - (void)setX2:(NSString *)x2 { - if (x2 == _x2) { + if ([x2 isEqualToString:_x2]) { return; } [self invalidate]; @@ -40,7 +40,7 @@ - (void)setX2:(NSString *)x2 - (void)setY2:(NSString *)y2 { - if (y2 == _y2) { + if ([y2 isEqualToString:_y2]) { return; } [self invalidate]; diff --git a/ios/Shapes/RNSVGRect.h b/ios/Shapes/RNSVGRect.h index 224aeef79..59d8f6533 100644 --- a/ios/Shapes/RNSVGRect.h +++ b/ios/Shapes/RNSVGRect.h @@ -14,8 +14,8 @@ @property (nonatomic, strong) NSString* x; @property (nonatomic, strong) NSString* y; -@property (nonatomic, strong) NSString* width; -@property (nonatomic, strong) NSString* height; +@property (nonatomic, strong) NSString* rectwidth; +@property (nonatomic, strong) NSString* rectheight; @property (nonatomic, strong) NSString* rx; @property (nonatomic, strong) NSString* ry; diff --git a/ios/Shapes/RNSVGRect.m b/ios/Shapes/RNSVGRect.m index ff5f587e5..8a9c8c373 100644 --- a/ios/Shapes/RNSVGRect.m +++ b/ios/Shapes/RNSVGRect.m @@ -13,7 +13,7 @@ @implementation RNSVGRect - (void)setX:(NSString *)x { - if (x == _x) { + if ([x isEqualToString:_x]) { return; } [self invalidate]; @@ -22,34 +22,34 @@ - (void)setX:(NSString *)x - (void)setY:(NSString *)y { - if (y == _y) { + if ([y isEqualToString:_y]) { return; } [self invalidate]; _y = y; } -- (void)setWidth:(NSString *)width +- (void)setRectwidth:(NSString *)rectwidth { - if (width == _width) { + if ([rectwidth isEqualToString:_rectwidth]) { return; } [self invalidate]; - _width = width; + _rectwidth = rectwidth; } -- (void)setHeight:(NSString *)height +- (void)setRectheight:(NSString *)rectheight { - if (height == _height) { + if ([rectheight isEqualToString:_rectheight]) { return; } [self invalidate]; - _height = height; + _rectheight = rectheight; } - (void)setRx:(NSString *)rx { - if (rx == _rx) { + if ([rx isEqualToString:_rx]) { return; } [self invalidate]; @@ -58,7 +58,7 @@ - (void)setRx:(NSString *)rx - (void)setRy:(NSString *)ry { - if (ry == _ry) { + if ([ry isEqualToString:_ry]) { return; } [self invalidate]; @@ -70,31 +70,31 @@ - (CGPathRef)getPath:(CGContextRef)context CGMutablePathRef path = CGPathCreateMutable(); CGFloat x = [self relativeOnWidth:self.x]; CGFloat y = [self relativeOnHeight:self.y]; - CGFloat width = [self relativeOnWidth:self.width]; - CGFloat height = [self relativeOnHeight:self.height]; + CGFloat width = [self relativeOnWidth:self.rectwidth]; + CGFloat height = [self relativeOnHeight:self.rectheight]; CGFloat rx = [self relativeOnWidth:self.rx]; CGFloat ry = [self relativeOnHeight:self.ry]; - + if (rx != 0 || ry != 0) { if (rx == 0) { rx = ry; } else if (ry == 0) { ry = rx; } - + if (rx > width / 2) { rx = width / 2; } - + if (ry > height / 2) { ry = height / 2; } - + CGPathAddRoundedRect(path, nil, CGRectMake(x, y, width, height), rx, ry); } else { CGPathAddRect(path, nil, CGRectMake(x, y, width, height)); } - + return (CGPathRef)CFAutorelease(path); } diff --git a/ios/Text/RNSVGTSpan.m b/ios/Text/RNSVGTSpan.m index e55862ba8..38a32e944 100644 --- a/ios/Text/RNSVGTSpan.m +++ b/ios/Text/RNSVGTSpan.m @@ -39,7 +39,7 @@ - (id)init - (void)setContent:(NSString *)content { - if (content == _content) { + if ([content isEqualToString:_content]) { return; } [self invalidate]; @@ -60,6 +60,7 @@ - (void)releaseCachedPath { CGPathRelease(_cache); _cache = nil; + self.path = nil; } - (void)dealloc diff --git a/ios/Text/RNSVGText.h b/ios/Text/RNSVGText.h index 548544b96..43b98592a 100644 --- a/ios/Text/RNSVGText.h +++ b/ios/Text/RNSVGText.h @@ -21,7 +21,6 @@ @property (nonatomic, strong) NSArray *positionY; @property (nonatomic, strong) NSArray *rotate; -- (void)releaseCachedPath; - (CGPathRef)getGroupPath:(CGContextRef)context; - (CTFontRef)getFontFromContext; diff --git a/ios/Text/RNSVGText.m b/ios/Text/RNSVGText.m index eda5ee3f3..b8c40c71a 100644 --- a/ios/Text/RNSVGText.m +++ b/ios/Text/RNSVGText.m @@ -16,6 +16,95 @@ @implementation RNSVGText { RNSVGGlyphContext *_glyphContext; + NSString *_alignmentBaseline; + NSString *_baselineShift; +} + +- (void)invalidate +{ + [super invalidate]; + [self releaseCachedPath]; +} + +- (void)setTextLength:(NSString *)textLength +{ + if ([textLength isEqualToString:_textLength]) { + return; + } + [self invalidate]; + _textLength = textLength; +} + +- (void)setBaselineShift:(NSString *)baselineShift +{ + if ([baselineShift isEqualToString:_baselineShift]) { + return; + } + [self invalidate]; + _baselineShift = baselineShift; +} + +- (void)setLengthAdjust:(NSString *)lengthAdjust +{ + if ([lengthAdjust isEqualToString:_lengthAdjust]) { + return; + } + [self invalidate]; + _lengthAdjust = lengthAdjust; +} + +- (void)setAlignmentBaseline:(NSString *)alignmentBaseline +{ + if ([alignmentBaseline isEqualToString:_alignmentBaseline]) { + return; + } + [self invalidate]; + _alignmentBaseline = alignmentBaseline; +} + +- (void)setDeltaX:(NSArray *)deltaX +{ + if (deltaX == _deltaX) { + return; + } + [self invalidate]; + _deltaX = deltaX; +} + +- (void)setDeltaY:(NSArray *)deltaY +{ + if (deltaY == _deltaY) { + return; + } + [self invalidate]; + _deltaY = deltaY; +} + +- (void)setPositionX:(NSArray*)positionX +{ + if (positionX == _positionX) { + return; + } + [self invalidate]; + _positionX = positionX; +} + +- (void)setPositionY:(NSArray*)positionY +{ + if (positionY == _positionY) { + return; + } + [self invalidate]; + _positionY = positionY; +} + +- (void)setRotate:(NSArray *)rotate +{ + if (rotate == _rotate) { + return; + } + [self invalidate]; + _rotate = rotate; } - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect @@ -26,7 +115,6 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect CGPathRef path = [self getGroupPath:context]; [self renderGroupTo:context rect:rect]; - [self releaseCachedPath]; CGContextRestoreGState(context); CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(path, &CGAffineTransformIdentity); @@ -36,18 +124,12 @@ - (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect - (void)setupGlyphContext:(CGContextRef)context { - _glyphContext = [[RNSVGGlyphContext alloc] initWithScale:1 width:[self getContextWidth] - height:[self getContextHeight]]; -} - -// release the cached CGPathRef for RNSVGTSpan -- (void)releaseCachedPath -{ - [self traverseSubviews:^BOOL(__kindof RNSVGNode *node) { - RNSVGText *text = node; - [text releaseCachedPath]; - return YES; - }]; + CGRect bounds = CGContextGetClipBoundingBox(context); + CGSize size = bounds.size; + _glyphContext = [[RNSVGGlyphContext alloc] + initWithScale:1 + width:size.width + height:size.height]; } - (CGPathRef)getGroupPath:(CGContextRef)context @@ -63,7 +145,6 @@ - (CGPathRef)getPath:(CGContextRef)context { [self setupGlyphContext:context]; CGPathRef groupPath = [self getGroupPath:context]; - [self releaseCachedPath]; return (CGPathRef)CFAutorelease(CGPathCreateCopyByTransformingPath(groupPath, &CGAffineTransformIdentity)); } @@ -95,7 +176,7 @@ - (NSString *)alignmentBaseline if (_alignmentBaseline != nil) { return _alignmentBaseline; } - + UIView* parent = self.superview; while (parent != nil) { if ([parent isKindOfClass:[RNSVGText class]]) { @@ -108,7 +189,7 @@ - (NSString *)alignmentBaseline } parent = [parent superview]; } - + if (_alignmentBaseline == nil) { _alignmentBaseline = RNSVGAlignmentBaselineStrings[0]; } @@ -120,7 +201,7 @@ - (NSString *)baselineShift if (_baselineShift != nil) { return _baselineShift; } - + UIView* parent = [self superview]; while (parent != nil) { if ([parent isKindOfClass:[RNSVGText class]]) { @@ -133,10 +214,10 @@ - (NSString *)baselineShift } parent = [parent superview]; } - + // set default value _baselineShift = @""; - + return _baselineShift; } diff --git a/ios/Text/RNSVGTextPath.m b/ios/Text/RNSVGTextPath.m index 939dc865f..bc21aa41f 100644 --- a/ios/Text/RNSVGTextPath.m +++ b/ios/Text/RNSVGTextPath.m @@ -112,6 +112,60 @@ @implementation RNSVGTextPath BOOL isClosed; } +- (void)setHref:(NSString *)href +{ + if ([href isEqualToString:_href]) { + return; + } + [self invalidate]; + _href = href; +} + +- (void)setSide:(NSString *)side +{ + if ([side isEqualToString:_side]) { + return; + } + [self invalidate]; + _side = side; +} + +- (void)setMethod:(NSString *)method +{ + if ([method isEqualToString:_method]) { + return; + } + [self invalidate]; + _method = method; +} + +- (void)setMidLine:(NSString *)midLine +{ + if ([midLine isEqualToString:_midLine]) { + return; + } + [self invalidate]; + _midLine = midLine; +} + +- (void)setSpacing:(NSString *)spacing +{ + if ([spacing isEqualToString:_spacing]) { + return; + } + [self invalidate]; + _spacing = spacing; +} + +- (void)setStartOffset:(NSString *)startOffset +{ + if ([startOffset isEqualToString:_startOffset]) { + return; + } + [self invalidate]; + _startOffset = startOffset; +} + - (void)getPathLength:(CGFloat*)lengthP lineCount:(NSUInteger*)lineCountP lengths:(NSArray* __strong *)lengthsP lines:(NSArray* __strong *)linesP isClosed:(BOOL*)isClosedP { RNSVGNode *template = [self.svgView getDefinedTemplate:self.href]; diff --git a/ios/Utils/RCTConvert+RNSVG.m b/ios/Utils/RCTConvert+RNSVG.m index 53655148d..f4e059b82 100644 --- a/ios/Utils/RCTConvert+RNSVG.m +++ b/ios/Utils/RCTConvert+RNSVG.m @@ -13,6 +13,8 @@ #import #import +NSRegularExpression *RNSVGDigitRegEx; + @implementation RCTConvert (RNSVG) RCT_ENUM_CONVERTER(RNSVGCGFCRule, (@{ @@ -27,9 +29,9 @@ @implementation RCTConvert (RNSVG) }), kRNSVGVBMOSMeet, intValue) RCT_ENUM_CONVERTER(RNSVGUnits, (@{ - @"objectBoundingBox": @(kRNSVGUnitsObjectBoundingBox), - @"userSpaceOnUse": @(kRNSVGUnitsUserSpaceOnUse), - }), kRNSVGUnitsObjectBoundingBox, intValue) + @"objectBoundingBox": @(kRNSVGUnitsObjectBoundingBox), + @"userSpaceOnUse": @(kRNSVGUnitsUserSpaceOnUse), + }), kRNSVGUnitsObjectBoundingBox, intValue) + (RNSVGCGFloatArray)RNSVGCGFloatArray:(id)json { @@ -54,6 +56,24 @@ + (RNSVGCGFloatArray)RNSVGCGFloatArray:(id)json + (RNSVGBrush *)RNSVGBrush:(id)json { + if ([json isKindOfClass:[NSString class]]) { + NSString *value = [self NSString:json]; + if (!RNSVGDigitRegEx) { + RNSVGDigitRegEx = [NSRegularExpression regularExpressionWithPattern:@"[0-9.-]+" options:NSRegularExpressionCaseInsensitive error:nil]; + } + NSArray *_matches = [RNSVGDigitRegEx matchesInString:value options:0 range:NSMakeRange(0, [value length])]; + NSMutableArray *output = [NSMutableArray array]; + NSUInteger i = 0; + [output addObject:[NSNumber numberWithInteger:0]]; + for (NSTextCheckingResult *match in _matches) { + NSString* strNumber = [value substringWithRange:match.range]; + [output addObject:[NSNumber numberWithDouble:(i++ < 3 ? strNumber.doubleValue / 255 : strNumber.doubleValue)]]; + } + if ([output count] < 5) { + [output addObject:[NSNumber numberWithDouble:1]]; + } + return [[RNSVGSolidColorBrush alloc] initWithArray:output]; + } NSArray *arr = [self NSArray:json]; NSUInteger type = [self NSUInteger:arr.firstObject]; @@ -124,3 +144,4 @@ + (CGGradientRef)RNSVGCGGradient:(id)json offset:(NSUInteger)offset } @end + diff --git a/ios/ViewManagers/RNSVGImageManager.m b/ios/ViewManagers/RNSVGImageManager.m index 5f965e3a8..d113536ee 100644 --- a/ios/ViewManagers/RNSVGImageManager.m +++ b/ios/ViewManagers/RNSVGImageManager.m @@ -25,8 +25,8 @@ - (RNSVGRenderable *)node RCT_EXPORT_VIEW_PROPERTY(x, NSString) RCT_EXPORT_VIEW_PROPERTY(y, NSString) -RCT_EXPORT_VIEW_PROPERTY(width, NSString) -RCT_EXPORT_VIEW_PROPERTY(height, NSString) +RCT_EXPORT_VIEW_PROPERTY(imagewidth, NSString) +RCT_EXPORT_VIEW_PROPERTY(imageheight, NSString) RCT_EXPORT_VIEW_PROPERTY(src, id) RCT_EXPORT_VIEW_PROPERTY(align, NSString) RCT_EXPORT_VIEW_PROPERTY(meetOrSlice, RNSVGVBMOS) diff --git a/ios/Brushes/RNSVGPattern.h b/ios/ViewManagers/RNSVGMaskManager.h similarity index 73% rename from ios/Brushes/RNSVGPattern.h rename to ios/ViewManagers/RNSVGMaskManager.h index b0a622c92..bb5fa5328 100644 --- a/ios/Brushes/RNSVGPattern.h +++ b/ios/ViewManagers/RNSVGMaskManager.h @@ -6,8 +6,8 @@ * LICENSE file in the root directory of this source tree. */ -#import "RNSVGBrush.h" +#import "RNSVGGroupManager.h" -@interface RNSVGPattern : RNSVGBrush +@interface RNSVGMaskManager : RNSVGGroupManager @end diff --git a/ios/ViewManagers/RNSVGMaskManager.m b/ios/ViewManagers/RNSVGMaskManager.m new file mode 100644 index 000000000..74483dd7b --- /dev/null +++ b/ios/ViewManagers/RNSVGMaskManager.m @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "RNSVGMaskManager.h" +#import "RNSVGMask.h" + +@implementation RNSVGMaskManager + +RCT_EXPORT_MODULE() + +- (RNSVGMask *)node +{ + return [RNSVGMask new]; +} + +RCT_EXPORT_VIEW_PROPERTY(x, NSString) +RCT_EXPORT_VIEW_PROPERTY(y, NSString) +RCT_EXPORT_VIEW_PROPERTY(maskwidth, NSString) +RCT_EXPORT_VIEW_PROPERTY(maskheight, NSString) +RCT_EXPORT_VIEW_PROPERTY(maskUnits, RNSVGUnits) +RCT_EXPORT_VIEW_PROPERTY(maskContentUnits, RNSVGUnits) +RCT_EXPORT_VIEW_PROPERTY(maskTransform, CGAffineTransform) + +@end diff --git a/ios/ViewManagers/RNSVGNodeManager.m b/ios/ViewManagers/RNSVGNodeManager.m index 50015ddce..556f4cc0d 100644 --- a/ios/ViewManagers/RNSVGNodeManager.m +++ b/ios/ViewManagers/RNSVGNodeManager.m @@ -24,14 +24,10 @@ - (UIView *)view return [self node]; } -- (RCTShadowView *)shadowView -{ - return nil; -} - RCT_EXPORT_VIEW_PROPERTY(name, NSString) RCT_EXPORT_VIEW_PROPERTY(opacity, CGFloat) RCT_EXPORT_VIEW_PROPERTY(matrix, CGAffineTransform) +RCT_EXPORT_VIEW_PROPERTY(mask, NSString) RCT_EXPORT_VIEW_PROPERTY(clipPath, NSString) RCT_EXPORT_VIEW_PROPERTY(clipRule, RNSVGCGFCRule) RCT_EXPORT_VIEW_PROPERTY(responsible, BOOL) diff --git a/ios/ViewManagers/RNSVGPatternManager.h b/ios/ViewManagers/RNSVGPatternManager.h new file mode 100644 index 000000000..05d546b6b --- /dev/null +++ b/ios/ViewManagers/RNSVGPatternManager.h @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "RNSVGGroupManager.h" + +@interface RNSVGPatternManager : RNSVGGroupManager + +@end diff --git a/ios/ViewManagers/RNSVGPatternManager.m b/ios/ViewManagers/RNSVGPatternManager.m new file mode 100644 index 000000000..a6e97b24f --- /dev/null +++ b/ios/ViewManagers/RNSVGPatternManager.m @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2015-present, Horcrux. + * All rights reserved. + * + * This source code is licensed under the MIT-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "RNSVGPatternManager.h" +#import "RNSVGPattern.h" + +@implementation RNSVGPatternManager + +RCT_EXPORT_MODULE() + +- (RNSVGPattern *)node +{ + return [RNSVGPattern new]; +} + +RCT_EXPORT_VIEW_PROPERTY(x, NSString) +RCT_EXPORT_VIEW_PROPERTY(y, NSString) +RCT_EXPORT_VIEW_PROPERTY(patternwidth, NSString) +RCT_EXPORT_VIEW_PROPERTY(patternheight, NSString) +RCT_EXPORT_VIEW_PROPERTY(patternUnits, RNSVGUnits) +RCT_EXPORT_VIEW_PROPERTY(patternContentUnits, RNSVGUnits) +RCT_EXPORT_VIEW_PROPERTY(patternTransform, CGAffineTransform) + +RCT_EXPORT_VIEW_PROPERTY(minX, CGFloat) +RCT_EXPORT_VIEW_PROPERTY(minY, CGFloat) +RCT_EXPORT_VIEW_PROPERTY(vbWidth, CGFloat) +RCT_EXPORT_VIEW_PROPERTY(vbHeight, CGFloat) +RCT_EXPORT_VIEW_PROPERTY(align, NSString) +RCT_EXPORT_VIEW_PROPERTY(meetOrSlice, RNSVGVBMOS) + +@end diff --git a/ios/ViewManagers/RNSVGRectManager.m b/ios/ViewManagers/RNSVGRectManager.m index c22e1e135..a4f3dce98 100644 --- a/ios/ViewManagers/RNSVGRectManager.m +++ b/ios/ViewManagers/RNSVGRectManager.m @@ -22,8 +22,8 @@ - (RNSVGRenderable *)node RCT_EXPORT_VIEW_PROPERTY(x, NSString) RCT_EXPORT_VIEW_PROPERTY(y, NSString) -RCT_EXPORT_VIEW_PROPERTY(width, NSString) -RCT_EXPORT_VIEW_PROPERTY(height, NSString) +RCT_EXPORT_VIEW_PROPERTY(rectwidth, NSString) +RCT_EXPORT_VIEW_PROPERTY(rectheight, NSString) RCT_EXPORT_VIEW_PROPERTY(rx, NSString) RCT_EXPORT_VIEW_PROPERTY(ry, NSString) diff --git a/ios/ViewManagers/RNSVGUseManager.m b/ios/ViewManagers/RNSVGUseManager.m index 1c3ad9cb6..5d490bc16 100644 --- a/ios/ViewManagers/RNSVGUseManager.m +++ b/ios/ViewManagers/RNSVGUseManager.m @@ -19,7 +19,7 @@ - (RNSVGNode *)node } RCT_EXPORT_VIEW_PROPERTY(href, NSString) -RCT_EXPORT_VIEW_PROPERTY(width, NSString) -RCT_EXPORT_VIEW_PROPERTY(height, NSString) +RCT_EXPORT_VIEW_PROPERTY(usewidth, NSString) +RCT_EXPORT_VIEW_PROPERTY(useheight, NSString) @end diff --git a/lib/attributes.js b/lib/attributes.js index 024f0045e..1798cda61 100644 --- a/lib/attributes.js +++ b/lib/attributes.js @@ -55,6 +55,7 @@ const NodeAttributes = { opacity: true, clipRule: true, clipPath: true, + mask: true, propList: { diff: arrayDiffer }, @@ -96,8 +97,8 @@ const GroupAttributes = { const UseAttributes = { ...RenderableAttributes, href: true, - width: true, - height: true + usewidth: true, + useheight: true, }; const SymbolAttributes = { @@ -161,6 +162,33 @@ const GradientAttributes = { } }; +const PatternAttributes = { + ...ViewBoxAttributes, + name: true, + x: true, + y: true, + patternwidth: true, + patternheight: true, + patternUnits: true, + patternContentUnits: true, + patternTransform: { + diff: arrayDiffer + } +}; + +const MaskAttributes = { + name: true, + x: true, + y: true, + maskwidth: true, + maskheight: true, + maskUnits: true, + maskContentUnits: true, + maskTransform: { + diff: arrayDiffer + } +}; + const LinearGradientAttributes = { ...GradientAttributes, x1: true, @@ -199,8 +227,8 @@ const ImageAttributes = { ...RenderableAttributes, x: true, y: true, - width: true, - height: true, + imagewidth: true, + imageheight: true, src: true, align: true, meetOrSlice: true @@ -218,8 +246,8 @@ const RectAttributes = { ...RenderableAttributes, x: true, y: true, - width: true, - height: true, + rectwidth: true, + rectheight: true, rx: true, ry: true }; @@ -240,5 +268,7 @@ export { SymbolAttributes, LinearGradientAttributes, RadialGradientAttributes, - ViewBoxAttributes + ViewBoxAttributes, + PatternAttributes, + MaskAttributes, }; diff --git a/lib/extract/extractProps.js b/lib/extract/extractProps.js index 6f5def49a..b6fed9da2 100644 --- a/lib/extract/extractProps.js +++ b/lib/extract/extractProps.js @@ -4,24 +4,40 @@ import extractTransform, { props2transform } from "./extractTransform"; import extractClipPath from "./extractClipPath"; import extractResponder from "./extractResponder"; import extractOpacity from "./extractOpacity"; +import urlRegex from "./patternReg"; export default function(props, ref) { + const { opacity, onLayout, id, clipPath, mask } = props; const styleProperties = []; const extractedProps = { - opacity: extractOpacity(props.opacity), + opacity: extractOpacity(opacity), propList: styleProperties, - onLayout: props.onLayout + onLayout, }; - if (props.id) { - extractedProps.name = props.id; + if (id) { + extractedProps.name = id; } - if (props.clipPath) { + if (clipPath) { Object.assign(extractedProps, extractClipPath(props)); } + if (mask) { + let matched = mask.match(urlRegex); + + if (matched) { + extractedProps.mask = matched[1]; + } else { + console.warn( + 'Invalid `mask` prop, expected a mask like `"#id"`, but got: "' + + mask + + '"' + ); + } + } + Object.assign(extractedProps, extractStroke(props, styleProperties)); Object.assign(extractedProps, extractFill(props, styleProperties)); diff --git a/lib/props.js b/lib/props.js index 93b249565..f8cff4d52 100644 --- a/lib/props.js +++ b/lib/props.js @@ -41,6 +41,10 @@ const clipProps = { clipPath: PropTypes.string }; +const maskProps = { + mask: PropTypes.string +}; + const definationProps = { name: PropTypes.string }; @@ -80,6 +84,7 @@ const pathProps = { ...fillProps, ...strokeProps, ...clipProps, + ...maskProps, ...transformProps, ...responderProps, ...touchableProps,