Drawable與Bitmap相互轉換

Bitmap和Drawable區別

Biamap轉換爲Drawable

  • Bitmap轉換爲Drawable
Drawable bitmapDrawable = new BitmapDrawable(bitmap);
imageView.setBackground(bitmapDrawable);

Drawable轉換爲Bitmap

將png格式drawable轉換爲Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), 
R.drawable.niuniu);
imageView.setImageBitmap(bitmap);
將xml格式的VectorDrawable轉換爲Bitmap
Drawable drawable = getResources().getDrawable(R.drawable.rotation);
Bitmap bitmap = DrawableToBitmap(drawable);imageView.setImageBitmap(bitmap);


private Bitmap DrawableToBitmap(Drawable drawable){
    Bitmap bitmap = null;
    int width = drawable.getIntrinsicWidth();
    int height = drawable.getIntrinsicHeight();
    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);
    return bitmap;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章