你能将VectorDrawable的pathData转换成Path对象吗?

12

能否从 VectorDrawable 中提取 pathData 并将其转换为 Path 对象?

我想创建一个自定义的 ViewOutlineProvider 并给它一个任意形状来剪切和投射阴影。如果可以直接使用 VectorDrawable 就更好了。

谢谢, ndh

1个回答

8

Android能否将VectorDrawable -> pathData转换为android.graphics.Path

介绍

我们需要:

github 上有 VectorMaster,它可以为您完成所有工作。

只需在应用的 build.gradle 中添加以下依赖项(参见包含的示例应用程序):

dependencies {
      compile 'com.sdsmdg.harjot:vectormaster:1.1.3'
}

这是一个使用它的测试应用程序的图像: 在此输入图像描述

设置

这里有一个可供使用的向量(pathData)...res\drawable\ic_heart.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:name="outline"
        android:pathData="M20.84,4.61a5.5,5.5 0,0 0,-7.78 0L12,5.67l-1.06,-1.06a5.5,5.5 0,0 0,-7.78 7.78l1.06,1.06L12,21.23l7.78,-7.78 1.06,-1.06a5.5,5.5 0,0 0,0 -7.78z"
        android:strokeLineCap="round"
        android:strokeColor="#5D5D5D"
        android:fillColor="#00000000"
        android:strokeWidth="2"
        android:strokeLineJoin="round"/>
</vector>

这是我们布局中的一个VectorMasterView:

...res\layout\activity_main

<com.sdsmdg.harjot.vectormaster.VectorMasterView
    android:id="@+id/heart_vector"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_margin="10dp"
    android:scaleX="0.8"
    android:scaleY="0.8"
    app:vector_src="@drawable/ic_heart" />

代码

onCreate中设置Vector

//normal stuff
setContentView(R.layout.activity_main);

//Inflate the `Vector`
VectorMasterView vmHeartVector = (VectorMasterView) findViewById(R.id.heart_vector);

// find the correct path using name
PathModel outline = vmHeartVector.getPathModelByName("outline");

String pathData   = outline.getPathData();// this is our pathData
Path   path       = outline.getPath();    // this is our path object;

一些链接: 矢量图形概述, 路径, pathData, VectorDrawable, AnimatedVectorDrawable, VectorDrawableCompat, AnimatedVectorDrawableCompat


对于那些寻找pathData->Path转换的人,这里是链接: https://github.com/harjot-oberai/VectorMaster/tree/master/vectormaster/src/main/java/com/sdsmdg/harjot/vectormaster/utilities/parser - Miha_x64
@Jon-Goodwin 我想将这个 pathData 绘制到画布上,如果一个单独的向量有多个 pathData,我想逐个将每个 pathData 绘制到画布上,因为我想在单击时允许拖动/飞行每个 pathdata。你能帮我吗?如何做到这一点? - Mujahid Khan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接