将边框/描边设置为矢量绘制可编程
问题描述:
我可以通过编程方式更改矢量绘制的颜色,但我想将描边应用于矢量绘制。我需要在运行时改变矢量绘制中风的方法:将边框/描边设置为矢量绘制可编程
以前我用这个方法,但在我的情况下失败。
我将Vector drawable转换为位图,然后将边框与此函数一起使用,但它用黑色填充所有,则不应用笔触。
private static Bitmap getBitmap(VectorDrawable vectorDrawable)
{
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
private static Bitmap getBitmap(Context context, int drawableId)
{
Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (drawable instanceof BitmapDrawable)
{
return ((BitmapDrawable) drawable).getBitmap();
}
else if (drawable instanceof VectorDrawable)
{
return getBitmap((VectorDrawable) drawable);
}
else
{
throw new IllegalArgumentException("unsupported drawable type");
}
}
private Bitmap addWhiteBorder(Bitmap bmp, int borderSize)
{
Bitmap bmpWithBorder = Bitmap.createBitmap(bmp.getWidth() + borderSize*2 , bmp.getHeight() + borderSize*2 , bmp.getConfig());
Canvas canvas = new Canvas(bmpWithBorder);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, borderSize, borderSize, null);
return bmpWithBorder;
}
答
假设您在VectorDrawable在vectordrawable.xml定义
<vector
android:width="100dp"
android:height="100dp"
android:viewportWidth="100"
android:viewportHeight="100">
<path
android:name="headset"
android:strokeColor="#FF000000"
android:strokeWidth="0"
...
android:pathData="..." />
</vector>
然后你就可以定义一个AnimatedVectorDrawable改变strokeWidth
<?xml version="1.0" encoding="utf-8"?>
<animated-vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/vectordrawable">
<target
android:animation="@animator/change_stroke_width"
android:name="headset" />
</animated-vector>
最后,定义改变strokeWidth动画in change_stroke_width.xml:
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<objectAnimator
android:duration="100"
android:propertyName="strokeWidth"
android:valueFrom="0"
android:valueTo="10" />
</set>
我认为这将绘制一个矩形边框周围的位图,而我想添加笔画/边界到矢量绘制路径(或从它创建的位图)@Doris – waqas
我添加了有问题的图片请参阅@Doris – waqas
是的,上面的答案会产生一个矩形边框。在看到您添加的图像后,我认为VectorDrawable可以用一条路径表示,在这种情况下,您需要定义strokeWidth和strokeColor以实现该黑色轮廓/边框。 –