drawable缩放

来源:互联网 发布:ecshop手机商城源码 编辑:程序博客网 时间:2024/06/08 13:41

一、 相关概念

1.       Drawable就是一个可画的对象,其可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable),还有可能是一个图层(LayerDrawable),我们根据画图的需求,创建相应的可画对象

2.       Canvas画布,绘制的目的区域,用于绘图

3.       Bitmap位图,用于图的处理

4.       Matrix矩阵,此例中用于操作图片

二、 步骤

1.       drawable画到位图对象上

2.       对位图对象做缩放(或旋转等)操作

3.       把位图再转换成drawable

三、示例
        static Bitmap drawableToBitmap(Drawabledrawable)//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并返回
0 0