2014-01-11 36 views
1

在畫布上繪製具有1種基本顏色的矩形很容易。但是,我需要能夠繪製具有以一種顏色開始的漸變並均勻轉換到另一種顏色的漸變。在畫布上繪製漸變形狀

我習慣使用xml文件繪製漸變背景。在畫布上繪製形狀時,是否有辦法引用xml文件?還是有更好的方法來繪製漸變形狀?

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_pressed="true"> 
     <layer-list> 
      <item> 
       <shape> 
        <!-- Gradient Bg for Button --> 
        <gradient 
          android:startColor="@color/button_type1_pushed" 
          android:endColor="@color/button_type1_pushed" 
          android:angle="270" /> 
        <stroke 
          android:width="0.05dp" 
          android:color="@color/button_type1_border"/> 
       </shape> 
      </item> 
     </layer-list> 
    </item> 

    <item android:state_enabled="true"> 
     <layer-list> 
      <item> 
       <shape android:shape="rectangle"> 
        <gradient 
         android:startColor="@color/button_type1_normal" 
         android:endColor="@color/button_type1_normal" 
         android:angle="90" /> 
        <stroke 
         android:width="0.05dp" 
         android:color="@color/button_type1_border"/>  
       </shape> 
      </item> 
     </layer-list> 
    </item> 
</selector> 

回答

2

您必須在作爲LinearGradient的繪製元素中創建着色器,然後在畫布中繪製一個矩形。

您可以通過繪製矩形的方式獲得水平和垂直漸變。

你可以看到一個代碼示例here

+0

工作很好!謝謝 – industrychanger

1

您可以將XML加載到Drawable,並且具有在畫布上繪製:

Drawable drawable = context.getResources().getDrawable(R.drawable.your_drawable); 
drawable.draw(canvas); 

documentation查看詳情。