How can I crop a bitmap for ImageView?

前端 未结 4 915

I know this should be simple , but android:scaleType=\"centerCrop\" doesn\'t crop Image

I got image 1950 pixels wide and need it to be cropped

相关标签:
4条回答
  • 2020-11-30 05:49

    You can do this programmatically (this ensures you get the right height/width):

    ImageView image = (ImageView) findVieById(R.id.ver_bottompanelprayer);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(1950, dm.heightPixels);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    image.setLayoutParams(params);
    image.setScaleType(ScaleType.FIT_XY);
    
    0 讨论(0)
  • 2020-11-30 05:53

    Alright, I will paste the comment as answer :) ->

    RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl1);
    
    final Options bitmapOptions=new Options();
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    bitmapOptions.inDensity = metrics.densityDpi;
    bitmapOptions.inTargetDensity=1;
    
    /*`final` modifier might be necessary for the Bitmap*/
    Bitmap bmp= BitmapFactory.decodeResource(getResources(), R.drawable.ver_bottom_panel_tiled_long, bitmapOptions);
    bmp.setDensity(Bitmap.DENSITY_NONE);
    bmp = Bitmap.createBitmap(bmp, 0, 0, rl.getWidth(), bmp.getHeight());
    

    Then in the code:

    ImageView iv = (ImageView)v.findViewById(R.id.ver_bottompanelprayer);
    if (iv != null){
      iv.setImageBitmap(bmp);
    }
    

    Cheers :)

    0 讨论(0)
  • 2020-11-30 05:56

    You can also crop image by programmatically using createBitmap.

    Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    bm = Bitmap.createBitmap(bm, 0, 0, 400, 400);
    your_imageview.setImageBitmap(bm);
    

    Here 400 is your width & height you can change as per your requirement.

    0 讨论(0)
  • 2020-11-30 06:01

    Make it android:scaleType="fitStart" and for android:layout_height="400px"

    0 讨论(0)
提交回复
热议问题