无法在Android上裁剪和缩放位图

时间:2015-09-22 03:07:09

标签: android bitmap

我正在尝试截取我的应用的截图,裁剪掉顶部并将其缩小。但无论是作物还是规模似乎都不起作用。这是我的代码:

            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap screenShot = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            //crop out 60 px from top and scale down 0.3 times size
            Matrix matrix = new Matrix();
            matrix.postScale(0.3f, 0.3f);
            Bitmap bitmap = Bitmap.createBitmap(screenShot,
                    0, 60,
                    screenShot.getWidth(),
                    screenShot.getHeight()-60,
                    matrix,
                    true);

2 个答案:

答案 0 :(得分:1)

我不知道为什么你的代码不起作用,但裁剪位图很容易

bitmap = Bitmap.createBitmap(
    bitmap,                    //the source
    0,                         //left position to start copy with
    60,                        //top position to start copy with
    bitmap.getWidth(),         //number of pixels in each row to be copied
    bitmap.getHeight() - 60    //number of rows to be copied
);

并且缩放位图很容易

bitmap = Bitmap.createScaledBitmap(
    bitmap,   //the source
    120,      //destination width
    120,      //destination height
    false     //filter
);

答案 1 :(得分:0)

private void performCrop() {

try {  Intent cropIntent = new Intent("com.android.camera.action.CROP");
          cropIntent.setDataAndType(imageUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("outputX", AppController.convertDpToPx(60));
            cropIntent.putExtra("outputY", AppController.convertDpToPx(60));
            cropIntent.putExtra("return-data", true);
            startActivityForResult(cropIntent, CROP_PIC);} catch (ActivityNotFoundException anfe) {
            //display an error message
           String errorMessage = "Whoops - your device doesn't support the crop action!";
         Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();

        }
    }

//此方法可帮助您将dp转换为px

public static int convertDpToPx(int dp) {
            float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, AppController.getInstance().getApplicationContext().getResources().getDisplayMetrics());
            return (int) px;
        }

//将位图转换为uri

   public Uri getImageUri(Context inContext, Bitmap inImage) {
      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
      inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
      String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
      return Uri.parse(path);
    }