java Android - working with image scaling/cropping

2019-02-15 22:53发布

问题:

Well, all this thing tortures me for long weeks, I set an Image 227 pixels high in scales it to 170 pixels even if I want it to be wrap_content whenever I do.

Ok. Here I take My Image which is 1950 pixels long (I put here a part of it so you can understand how it should look like).

First, I want to scale it back to 227 pixels high because that's how it was designed and how it should be

Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ver_bottom_panel_tiled_long);
            int width = bitmapOrg.getWidth();
        int height = bitmapOrg.getHeight();
        int newWidth = 200; //this should be parent's whdth later
        int newHeight = 227;

        // calculate the scale
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // create a matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);

        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, 
                          width, height, matrix, true); 


        BitmapDrawable dmpDrwbl=new BitmapDrawable(resizedBitmap);

    verbottompanelprayer.setBackgroundDrawable(dmpDrwbl);

so... it's not a cropped image at all - no, it's 1950 pixels pressed into 200 pixels.

But I want just cut anything besides this 200 pixels or whatever width I'll set - crop it and not press all this long image into 200 pixels area.

Also, BitmapDrawable(Bitmap bitmap); and imageView.setBackgroundDrawable(drawable); are deprecated - how can I change that?

回答1:

according to what i see, you create a bitmap of the new size (200x227) , so i'm not sure what you expected. you've even written in the comments that you scale and no word on cropping...

what you can do is :

  1. if the API is at least 10 (gingerbread) , you can use BitmapRegionDecoder , using decodeRegion :

  2. if the API is too old, you need to decode the large bitmap, and then crop it into a new bitmap, using Bitmap.createBitmap

something like this:

final Rect rect =...
if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD_MR1)
  {
  BitmapRegionDecoder decoder=BitmapRegionDecoder.newInstance(imageFilePath, true);
  croppedBitmap= decoder.decodeRegion(rect, null);
  decoder.recycle();
  }
else 
  {
  Bitmap bitmapOriginal=BitmapFactory.decodeFile(imageFilePath, null);
  croppedBitmap=Bitmap.createBitmap(bitmapOriginal,rect.left,rect.top,rect.width(),rect.height());
  }