2010-07-21 28 views
2

給定一張圖像,我想只能縮放該圖像的一部分。說,我想擴大一半的圖像,這樣就佔了整個空間的一半。Android:調整圖像大小並縮放一部分

這怎麼可能?

將ImageView fitXY工作,因爲我認爲它只適用於整個原始圖像。

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = new LinearLayout(this); 

      Bitmap bitmap = BitmapFactory.decodeResource(getResources(),  R.drawable.icon); 


      int width = bitmap.getWidth(); 

      int height = bitmap.getHeight(); 

      int newWidth = 640; 

      int newHeight = 480; 


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

      float scaleHeight = ((float) newHeight)/height; 


      Matrix matrix = new Matrix(); 

      matrix.postScale(scaleWidth, scaleHeight); 

      // create the new Bitmap object 

      Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 50, 50, width, 

        height, matrix, true); 

      BitmapDrawable bmd = new BitmapDrawable(resizedBitmap); 



      ImageView imageView = new ImageView(this); 

      imageView.setImageDrawable(bmd); 

      imageView.setScaleType(ScaleType.CENTER); 



      linearLayout.addView(imageView, new LinearLayout.LayoutParams( 

        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 

      setContentView(linearLayout); 
    } 
} 

這隻有在createBitmap,X和源中的第一像素的y座標是0的意思,我不能夠採取的形象的一個子集。只能夠縮放整個圖像。但createBitmap是爲了圖像的子集。

在日誌中,當參數不爲0,我得到以下異常:java.lang.IllegalArgumentException異常:X +寬度必須< = bitmap.width()

請幫

回答

1

所以我不得不修復一些錯別字,但這個例子對我來說做得很好。 http://www.anddev.org/resize_and_rotate_image_-_example-t621.html 錯別字:

int width = bitmapOrg.width(); 
int height = bitmapOrg.height(); 

成爲:

int width = bitmapOrg.getWidth(); 
int height = bitmapOrg.getHeight(); 

否則,工作時,我嘗試了agains SDK 7

2

首先,你必須創建出一種新的位圖,你想用規模

createBitmap() //pass the source bitmap, req height and width 

現在從結果位圖中,你必須創建一個使用

createScaledbitmap() //pass the result bitmap , req width, height 

對於exapmle您縮放位圖:

Bitmap originalBitmap = BitmapFactory.decodeResource(res, id); 
Bitmap partImage = originalBitmap.createBitmap(width, height, config); 
Bitmap scaledImage = partImage.createScaledBitmap(partImage, dstWidth, dstHeight, filter); 
相關問題