48

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>

ドローアブルからビットマップを取得する私の方法:

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

渡された ID がshadow.xmlドローアブル IDの場合、getBitmap() は null を返します。

4

3 に答える 3

76

これは完全に機能するソリューションです:

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>
于 2016-02-23T10:22:28.690 に答える
14

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

于 2012-04-11T17:45:51.240 に答える