有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android以编程方式处理图像缩放/裁剪

好吧,这一切折磨了我好几个星期,我设置了一个227像素高的图像,并将其缩放到170像素,即使我希望它在任何时候都是wrap_内容

嗯。在这里,我拍摄了1950像素长的图像(我把它的一部分放在这里,这样你就可以理解它应该是什么样子了)

enter image description here

首先,我想把它缩小到227像素高,因为它是这样设计的,它应该是这样的

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

所以。。。这根本不是一个裁剪过的图像-不,它是1950像素压缩成200像素。 enter image description here

但我只想剪切200像素以外的任何东西,或者我将设置的任何宽度-裁剪它,而不是将所有这些长图像压入200像素区域

此外,位图可绘制(位图);和imageView。可拉拔(可拉拔);已弃用-如何更改


共 (1) 个答案

  1. # 1 楼答案

    根据我看到的,您创建了一个新大小(200x227)的位图,所以我不确定您期望的是什么。你甚至在评论中写下了你的规模和没有字的裁剪

    您可以做的是:

    1. 如果API至少为10(姜饼),则可以使用BitmapRegionDecoder,使用decodeRegion:

    2. 如果API太旧,则需要解码大位图,然后使用Bitmap.createBitmap将其裁剪成新位图

    大概是这样的:

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