歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 在Android中實現圖片縮放和旋轉

在Android中實現圖片縮放和旋轉

日期:2017/3/1 10:19:30   编辑:Linux編程

在Android中實現圖片縮放和旋轉

  1. btn.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v) {
  4. i = ++i;
  5. ImageView view = (ImageView)findViewById(R.id.imgView);
  6. // 1、首先加載要操作的圖片
  7. Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aa);
  8. //2、得到以上加載圖片的高度跟寬度
  9. int height = bitmap.getHeight();
  10. int width = bitmap.getWidth();
  11. //3、定義要縮放成最終的圖片高度跟寬度
  12. int nHeight = 150;
  13. int nWidth = 180;
  14. //4、計算縮放比例
  15. float scaleWidth = ((float) nWidth)/width;
  16. float scaleHeight = ((float) nHeight)/height;
  17. //5、創建Matrix對象 Matrix是在Android中用於操作圖像的類
  18. Matrix matrix = new Matrix();
  19. //6、使用Matrix對象跟縮放比例實現縮放圖片
  20. matrix.postScale(scaleWidth, scaleHeight);
  21. //同樣的,圖片旋轉只需要通過Matrix改變圖片角度即可,生成圖片跟7相同。
  22. Log.i("chens", "======i======"+i);
  23. if (i % 2 ==0 ) {
  24. matrix.postRotate(60);
  25. }else {
  26. matrix.postRotate(0);
  27. }
  28. //7、生成縮放後的圖片
  29. Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,width, height, matrix, true);
  30. view.setImageBitmap(resizedBitmap);
  31. }
  32. });
Copyright © Linux教程網 All Rights Reserved