Android: how to draw .svg file's elements sepa

2019-08-08 16:24发布

I have .svg a file with some elements in it. Is there any way to draw them step by step on the canvas?

I'm using com.caverock:androidsvg library, but it seems like there is no way to extract individual element.

1条回答
小情绪 Triste *
2楼-- · 2019-08-08 17:16

Here is my test example video. I copied one Path from 250 (the white outline in the middle of the image, that does not pan or scroll). It was the first Path in the SVG document, and the first element in the List of Path's
enter image description here

"I have .svg file with some elements in it. Is there any way to draw them step by step on the canvas?"

Yes you can do this (at least for the important Path data), see Android path tracing tutorial, and the source code in the github here. The demo (road-trip) extracts (actually it intercepts) the Path's and also animates these android.graphics.Path's (with android.animation.ObjectAnimator). You Tube.

The library I picked, androidsvg, is easy to use but does not give access to the paths contained in the SVG document. I worked around this issue by creating a custom Canvas that intercepts drawPath() calls:

//list of Path's
private final List<VecPath> mPaths = new ArrayList<VecPath>();

Canvas canvas = new Canvas() {
    private final Matrix mMatrix = new Matrix();

    @Override
    public void drawPath(Path path, Paint paint) {
        Path dst = new Path();

        // Get the current transform matrix
        getMatrix(mMatrix);
        // Apply the matrix to the path
        path.transform(mMatrix, dst);
        // Store the transformed path
        mPaths.add(new SvgPath(dst, new Paint(mSourcePaint)));
    }
};

// Load an SVG document
SVG svg = SVG.getFromResource(context, R.raw.map_usa);
// Capture the paths
svg.renderToCanvas(canvas);

Note

Remember the .SVG format is a document file, not just a simple vector image type. You possibly could modify the viewBox to select different images from your .SVG document, using the code above.

<svg
   width="650"
   height="1000"
   viewBox="40 350 900 1050"
   id="svg1">
查看更多
登录 后发表回答