android 实用的Bitmap处理函数

来源:互联网 发布:独立域名邮箱 编辑:程序博客网 时间:2024/06/05 20:45
在做android 开发的时候,特别是游戏开发,经常会用到不同大小的图片,比如:适配不同屏大小、以及不同的地方需要不同大小的图片等等。

这里给出一个将图片放大、缩小的处理函数:


/**
* bgimage  需要处理的图片
*  newWidth 、newHeight 这张图片处理后的宽高,这里newWidth 和 newHeight 其有效值是>= 0; 当其中一个值为0时候,表示按等宽* 高比来放大或是缩小。如果两个值都为0,则不进行放大缩小。
*  recy_the_bitmap 其值是一个boolean 值。其作用是:对bgimage  这张图片处理完成后是否回收其资源,对于手机这样的移动设备开发,其资源非常有限,这个是必须的。
  **/

  public static Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight, boolean recy_the_bitmap) { // 记得函数声明为static 
            int width;   
            int height;  
            Bitmap bitmap_mage = null;

             if(bgimage != null && !(newWidth==0 && newHeight==0)) 
                {
                    float scaleWidth = 1.0f;
                    float scaleHeight = 1.0f;

                    width = bgimage.getWidth(); 
                    height = bgimage.getHeight();
                    Matrix matrix = new Matrix();

                     if(newWidth > 0)
                     {
                          scaleWidth = ((float) newWidth) / width;  
                     }
                     if(newHeight > 0)
                      {
                          scaleHeight = ((float) newHeight) / height; 
                       }
     
                     if(scaleWidth == 1.0f)
                      {
                          scaleWidth = scaleHeight;
                       }
     
                     if(scaleHeight == 1.0f)
                     {
                      scaleHeight = scaleWidth;
                      }

                     matrix.postScale(scaleWidth, scaleHeight);   
                     bitmap_mage = Bitmap.createBitmap(bgimage, 0, 0, width, height,   
                       matrix, true);

                 }


           if(bitmap_mage != null)
            {
                 if(recy_the_bitmap)
                 {// 回收资源
                  bgimage.recycle();
                  bgimage = null;
                  }
                 return bitmap_mage;
             }
        else
            {
                 return bgimage;
             }


有什么不妥的地方请大家指出,

0 0
原创粉丝点击