2017-07-18 155 views
-1

我已經看了很多關於如何改變drawable的大小的線程,但他們都沒有工作。ScaleDrawable似乎沒有工作

位圖拋出類拋出異常,甚至設置ScaleDrawable的級別不起作用。

怎麼了?我不是在尋找一個xml解決方案,因爲我想根據屏幕的大小來根據其他項目的大小來調整大小。

謝謝。

//set seekbar thumb to height of bar 
     Drawable thumb = mSeekBarSpeed.getThumb(); 
     thumb = new ScaleDrawable(thumb, 0, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight()); 
     thumb.setLevel(10000); 
     thumb.setBounds(0, 0, thumb.getIntrinsicWidth(), thumb.getIntrinsicHeight()); 
//  Bitmap thumbBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.seekbar_thumb); 
//  Bitmap scaled = Bitmap.createScaledBitmap(thumbBitmap, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight(), true); 
//// 
////  Bitmap thumb = Bitmap.createBitmap(50,50, Bitmap.Config.ARGB_8888); 
////  Canvas canvas=new Canvas(thumb); 
////  canvas.drawBitmap(bitmap,new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), 
////    new Rect(0,0,thumb.getWidth(),thumb.getHeight()),null); 
////  Drawable drawable = new BitmapDrawable(getResources(),thumb); 
////  setThumb(drawable); 
// 
//  //Drawable thumb = mSeekBarSpeed.getThumb(); 
////  thumb.setBounds(0,0, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight()); 
////  Bitmap orig = ((BitmapDrawable)thumb).getBitmap(); 
////  Bitmap scaled = Bitmap.createScaledBitmap(orig, thumb.getIntrinsicWidth(), mSeekBarSpeed.getHeight(), true); 
//  Drawable newThumb = new BitmapDrawable(getResources(), scaled); 
//  newThumb.setBounds(0,0,newThumb.getIntrinsicWidth(),newThumb.getIntrinsicHeight()); 
     mSeekBarSpeed.setThumb(thumb); 

回答

0

找到一種方法讓它使用位圖工作。

Drawable thumb = mSeekBarSpeed.getThumb(); //get thumb of seekBar 

    Bitmap thumbBitmap; //try to find bitmap of thumb 
    if(thumb instanceof BitmapDrawable) { 
     thumbBitmap = ((BitmapDrawable)thumb).getBitmap(); 
    }else{ 
     Bitmap bitmap = Bitmap.createBitmap(thumb.getIntrinsicWidth(),thumb.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 
     thumb.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 
     thumb.draw(canvas); 
     thumbBitmap = bitmap; 
    } 

    //scale the bitmap 
    float scale = (float)1.00 * mSeekBarSpeed.getHeight()/thumb.getIntrinsicHeight(); 
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbBitmap, 
      Math.round(thumb.getIntrinsicWidth() * scale), 
      Math.round(thumb.getIntrinsicHeight() * scale), true); 

    //make is a drawable 
    Drawable newThumb = new BitmapDrawable(getResources(), scaledBitmap); 

    //set thumb to new thumb 
    mSeekBarSpeed.setThumb(newThumb); 

來源:Get All Installed Application icons in Android : java.lang.ClassCastException有一些關於位圖的類轉換異常的信息。