2012-04-11 3 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에는 비트 맵이 연결되어 있지 않습니다. 유일한 용도는 캔버스에 그려지는 것입니다. draw 메소드가 불려 갈 때까지, 이미지는 없습니다. 그림자를 그려야하는 곳에 canvas 요소를 가져올 수있는 경우 shapeDrawable로 그릴 수 있습니다. 그렇지 않으면 그림자를 배경으로하여 레이아웃에서 별도의 빈보기가 필요할 수 있습니다.

+0

좋은 설명에 감사드립니다. 캔버스에 직접 그려서 잘 작동했습니다. – kaneda

+0

@ kaneda 마지막으로 작동 한 코드를 표시 할 수 있습니까? 나는 여기 같은 문제에 직면하고있다. 고마워. –

+0

그럴 줄 알았는데 'Drawable d = getContext(). getResources(). getDrawable (R.drawable.id);' 'd.draw (canvas);' – 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

너비와 높이가> 0이어야한다. – BMU

+0

단지 사소한 호환성 업데이트 : "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> 
관련 문제