2016-11-18 41 views
1

我可以通過編程方式更改矢量繪製的顏色,但我想將描邊應用於矢量繪製。我需要在運行時改變矢量繪製中風的方法:將邊框/描邊設置爲矢量繪製可編程

enter image description here

以前我用這個方法,但在我的情況下失敗。

我將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; 
    } 

回答

0

假設您在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> 
+0

我認爲這將繪製一個矩形邊框周圍的位圖,而我想添加筆畫/邊界到矢量繪製路徑(或從它創建的位圖)@Doris – waqas

+0

我添加了有問題的圖片請參閱@Doris – waqas

+0

是的,上面的答案會產生一個矩形邊框。在看到您添加的圖像後,我認爲VectorDrawable可以用一條路徑表示,在這種情況下,您需要定義strokeWidth和strokeColor以實現該黑色輪廓/邊框。 –