2016-12-12 18 views
1

我嘗試layer-list轉換爲bitmap,然後設置這個bitmap作爲一個ImageView背景,但它不工作轉換層列表爲位圖不工作可能

這是一個測試項目。我知道我可以直接設置繪製到ImageView的,但我想知道爲什麼當我轉換LayerDrawableBitmap然後將其轉換BitmapBitmapDrawable然後將其設置爲ImageView的背景,它會尋找不同的
這裏是我的層列表(ic_circle .XML

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" 
    > 
    <item> 
     <shape 
      android:shape="oval"> 
      <solid android:color="#f00"></solid> 

     </shape> 
    </item> 
    <item 
     android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"> 
     <shape 
      android:shape="oval"> 
      <solid android:color="#ff0"></solid> 

     </shape> 
    </item> 
    <item 
     android:bottom="6dp" android:left="6dp" android:right="6dp" android:top="6dp"> 
     <shape 
      android:shape="oval"> 
      <solid android:color="#0ff"></solid> 
     </shape> 
    </item> 
</layer-list> 

活動代碼

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ImageView img = (ImageView) findViewById(R.id.img); 
     Bitmap bm = drawableToBitmap(ContextCompat.getDrawable(this, R.drawable.ic_circle)); 
     img.setBackground(new BitmapDrawable(bm)); 
    } 

    public Bitmap drawableToBitmap (Drawable drawable) { 
     int width = drawable.getIntrinsicWidth(); 
     width = width > 0 ? width : 1; 
     int height = drawable.getIntrinsicHeight(); 
     height = height > 0 ? height : 1; 

     Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 
     drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
     drawable.draw(canvas); 

     return bitmap; 
    } 
} 

XML代碼

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    > 

    <ImageView 
     android:layout_width="80dp" 
     android:layout_height="80dp" 
     android:background="@drawable/ic_circle" 
     /> 


    <ImageView 
     android:id="@+id/img" 
     android:layout_marginTop="40dp" 
     android:layout_width="80dp" 
     android:layout_height="80dp" 
     /> 

</LinearLayout> 

在模擬器中,你會看到第二圖像是第一圖像不同

enter image description here

+0

'我嘗試將圖層列表轉換爲位圖,然後將此位圖設置爲ImageView的背景'這對我來說沒有任何意義。介意解釋**你爲什麼要**?我的意思是,爲什麼不直接使用層列表並節省寶貴的機器週期? –

+0

@Rotwang這只是一個測試,我有一個轉換層位列表到位圖的問題,所以我創建這個項目 –

+1

爲什麼你要將它轉換爲位圖..你可以直接設置繪製圖像視圖.. – Meenal

回答

2

在你繪製你有你定義了只有2個外小圓圈(黃色和紅色)邊界,藍色的應該採取所有的休息空間。但是由於它沒有定義大小,所以一旦你在畫布上繪製它,它的大小將爲0.

如果要直接在位圖上繪製它,則必須定義它的大小。