Android:如何以编程方式为矢量绘图设置笔触颜色

时间:2015-12-22 09:43:07

标签: android android-vectordrawable

我在Android中遇到了VectorDrawable的麻烦。 我有一个矢量可绘制文件(.xml),我想在位图上绘制它。我设法加载这个文件并在位图上绘制它。我可以改变它的填充颜色,但问题是我不能改变它的笔触和颜色。

任何帮助都将不胜感激!!!

谢谢!

这是可绘制文件:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="312dp"
    android:height="312dp"
    android:viewportWidth="312.7"
    android:viewportHeight="312.699">
<path
    android:pathData="M306.35,266.34c0,22.09 -17.91,40.01 -40,40.01L46.35,306.35c-22.09,0 -40,-17.92 -40,-40.01v-219.99c0,-22.11 17.92,-40 40,-40h220c22.09,0 40,17.9 40,40L306.35,266.34z"
    android:strokeWidth="5"
    android:fillColor="@color/transparent"
    android:strokeColor="#231F20"/></vector>

这是我用蓝色加载和填充形状的方式:

Drawable drawable = getResources().getDrawable(R.drawable.graph_rounded_rectangle);
        drawable.setBounds(0, 0, width, height);
        drawable.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.blue), PorterDuff.Mode.MULTIPLY));
        drawable.draw(canvas);

3 个答案:

答案 0 :(得分:10)

正如Chris Banes中的his blog所述,您可以使用支持库为您的drawable着色,并使用以下代码:

Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_asset);

// Wrap the drawable so that future tinting calls work
// on pre-v21 devices. Always use the returned drawable.
drawable = DrawableCompat.wrap(drawable);

// We can now set a tint
DrawableCompat.setTint(drawable, Color.RED);
// ...or a tint list
DrawableCompat.setTintList(drawable, myColorStateList);
// ...and a different tint mode
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_OVER);

答案 1 :(得分:4)

尝试在group中添加xml,如下所示:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="312dp"
    android:height="312dp"
    android:viewportWidth="312.7"
    android:viewportHeight="312.699">
    <group android:scaleX="1.0" android:scaleY="1.0">
        <path
            android:pathData="M306.35,266.34c0,22.09 -17.91,40.01 -40,40.01L46.35,306.35c-22.09,0 -40,-17.92 -40,-40.01v-219.99c0,-22.11 17.92,-40 40,-40h220c22.09,0 40,17.9 40,40L306.35,266.34z"
            android:strokeWidth="5"
            android:fillColor="@color/transparent"
            android:strokeColor="#231F20"/>
    </group>
</vector>

参考here

答案 2 :(得分:0)

您只能在Java API中访问这些向量属性

Vector : name
Vector : width
Vector : height
Vector : viewportWidth
Vector : viewportHeight
Vector : tint
Vector : tintMode
Vector : autoMirrored
Vector : alpha

用于通过使用java代码设置向量的调用(颜色,大小等)是不可访问的。你必须用drawable来处理它。