如何为ImageView裁剪位图?

use*_*594 7 java android crop imageview

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

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

抱歉,简单的问题 - 尝试谷歌 - 只有复杂的问题.而且我是新人,所以请不要请求.

<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>
Run Code Online (Sandbox Code Playgroud)

如果有唯一的方法是programmaticaly裁剪它 - 请给我一个方法的建议

g00*_*0dy 15

好吧,我会将评论粘贴为答案:) - >

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());
Run Code Online (Sandbox Code Playgroud)

然后在代码中:

ImageView iv = (ImageView)v.findViewById(R.id.ver_bottompanelprayer);
if (iv != null){
  iv.setImageBitmap(bmp);
}
Run Code Online (Sandbox Code Playgroud)

干杯:)


Nir*_*tel 8

您还可以使用createBitmap以编程方式裁剪图像.

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
bm = Bitmap.createBitmap(bm, 0, 0, 400, 400);
your_imageview.setImageBitmap(bm);
Run Code Online (Sandbox Code Playgroud)

这里400是您的宽度和高度,您可以根据您的要求更改.