簡體   English   中英

無法在Android上裁剪和縮放位圖

[英]Unable to crop and scale a bitmap on Android

我正在嘗試拍攝我的應用程序的屏幕截圖,裁剪出頂部並縮小比例。 但是,收成和規模似乎都行不通。 這是我的代碼:

            // 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);

我不知道為什么您的代碼不起作用,但是裁剪位圖很容易

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
);
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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM