如何裁剪 ImageView 的位图?

2022-01-24 00:00:00 crop android java imageview

我知道这应该很简单,但是 android:scaleType="centerCrop" 不会裁剪图像

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

我的图像 1950 像素 宽,需要按照父级的宽度进行裁剪.但是 android:scaleType="centerCrop" 不会裁剪图像.我需要在布局中做什么才能仅显示前 400 像素,例如,或者任何屏幕/父宽度是

I got image 1950 pixels wide and need it to be cropped by parent's width. But android:scaleType="centerCrop" doesn't crop Image. What do I need to do in layout to show only first 400 pixels, for instance or whatever screen/parent width is

抱歉,问题很简单 - 尝试用谷歌搜索 - 那里只有复杂的问题.而且我是新人,所以请不要投反对票)

Sorry for simple question - tried to Google it - only complicated questions there. And I'm new, so don't downvote please)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_color">

    <ImageView
            android:id="@+id/ver_bottompanelprayer"
            android:layout_width="match_parent"
            android:layout_height="227px"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:scaleType="matrix"

            android:background="@drawable/ver_bottom_panel_tiled_long" />

</RelativeLayout>

如果唯一的方法是通过编程方式裁剪它 - 请给我一个方法的建议

if there's only way is to programmaticaly crop it - please give me an advice with a method

推荐答案

好的,我将把评论粘贴为答案:) ->

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

然后在代码中:

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

干杯:)

相关文章