Android縮放drawable

來源:互聯網
上載者:User

一、
 


相關概念

1.
       



Drawable
就是一個可畫的
對象,其可能是一張位元影像(

BitmapDrawable
),也可能是一個
圖形(

ShapeDrawable
),還有可能是一
個圖層(

LayerDrawable
),我們根據畫圖的需求,建立相應的可畫對象

2.
       



Canvas
畫布,繪製的目
的地區,用於繪圖

3.
       



Bitmap
位元影像,用於圖的
處理

4.
       



Matrix
矩陣,此例中用
於操作圖片

二、
 



步驟

1.
       



把

drawable
畫到位元影像對象上

2.
       



對位元影像對象做縮放(或旋轉等)操作

3.
       



把位元影像再轉換成

drawable

三、




樣本



        
static Bitmap
drawableToBitmap(Drawable drawable)


// drawable
轉換成


bitmap

        
{
                  
int width =
drawable.getIntrinsicWidth();  


//

取

drawable
的長寬



                  
int
height = drawable.getIntrinsicHeight();
                

Bitmap.Config config = drawable.getOpacity() !=
PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565;        


//
取

drawable
的顏色格式



                  
Bitmap
bitmap = Bitmap.createBitmap(width, height, config);    



//
建立對應


bitmap

                  
Canvas canvas = new Canvas(bitmap);        


//

建立對應

bitmap
的畫布



                  
drawable.setBounds(0,
0, width, height);
                  
drawable.draw(canvas);     


//
把

drawable
內容畫到畫布中



                  
return
bitmap;
        
}

        

static Drawable zoomDrawable(Drawable drawable, int w, int h)
        
{
                  
int
width = drawable.getIntrinsicWidth();
                  

int height= drawable.getIntrinsicHeight();
                  

Bitmap oldbmp = drawableToBitmap(drawable);


// drawable
轉換成


bitmap

                  

Matrix matrix = new Matrix();  


//

建立操作圖片用的

Matrix
對象



                  
float
scaleWidth = ((float)w / width);  


//
計算縮放比例



                  
float scaleHeight = ((float)h /
height);
                  
matrix.postScale(scaleWidth,
scaleHeight);        


//
設定縮放比例



                  
Bitmap newbmp =
Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);      


//
建立新的

bitmap
,其內容是對原

bitmap
的縮放後的圖



                  
return
new BitmapDrawable(newbmp);      


//
把

bitmap
轉換成

drawable
並返回



        
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.