2012-04-11 6 views
25

どのようにしてビットマップをXML形状のドロウアブルから得ることができますか? 私は何が間違っていますか?xmlで定義されたドロアブルからビットマップを取得する方法は?

shadow.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" > 

    <gradient 
     android:angle="270.0" 
     android:endColor="@android:color/transparent" 
     android:startColor="#33000000" 
     android:type="linear" /> 

    <size android:height="7.0dip" /> 

</shape> 

描画可能からビットマップを取得するための私の方法:渡されたidがshadow.xmlとき

private Bitmap getBitmap(int id) { 
    return BitmapFactory.decodeResource(getContext().getResources(), id); 
} 

getBitmap()がnullを返している drawable id。

答えて

13

ShapeDrawableにはビットマップが関連付けられていません。その唯一の目的はキャンバスに描画されることです。描画メソッドが呼び出されるまで、画像はありません。影を描画する必要がある場所にキャンバス要素を配置することができれば、shapeDrawableとして描くことができます。そうでない場合は、影を背景にレイアウト内に別の空のビューが必要になることがあります。

+0

良い説明をありがとう。私はそれをキャンバスに直接描き、うまく働いた。 – kaneda

+0

@ kaneda最終的に動作したコードを表示できますか?私はここで同じ問題に直面している。どうもありがとう。 –

+0

これは、 の描画可能なd = getContext()、getResources()、getDrawable(R.drawable.id)、 ' ' d.draw(キャンバス); ' – Punksmurf

27

これは完全に作業溶液です:

private Bitmap getBitmap(int drawableRes) { 
    Drawable drawable = getResources().getDrawable(drawableRes); 
    Canvas canvas = new Canvas(); 
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 
    canvas.setBitmap(bitmap); 
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); 
    drawable.draw(canvas); 

    return bitmap; 
} 

そして、ここでの例です:

Bitmap drawableBitmap = getBitmap(R.drawable.circle_shape); 

circle_shape.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval"> 
    <size 
     android:width="15dp" 
     android:height="15dp" /> 
    <solid 
     android:color="#94f5b6" /> 
    <stroke 
     android:width="2dp" 
     android:color="#487b5a"/> 
</shape> 
あなたが追加する必要があり
+1

これは、受け入れられる答えでなければなりません – blueware

+0

それはjava.lang.IllegalArgumentExceptionをスローします:widthとheightは> 0でなければなりません – BMU

+0

ちょっとした互換性のアップデート:change "getResources()。getDrawable(drawableRes);" "ContextCompat.getDrawable(context、drawableRes);" – Tobliug

0

サイズ属性あなたのシャーに"java.lang.IllegalArgumentException:幅と高さが> 0である必要があります。

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="oval"> 
     <solid android:color="@color/colorAccent" /> 
     <stroke 
      android:width="1.3dp" 
      android:color="@color/white" /> 

     <size android:height="24dp" android:width="24dp"/> 
</shape> 
関連する問題